图片切割裁剪

图片切割裁剪

920 发布: 2021/8/26 10:36 本文总阅读量

iOS图片多样性裁剪

要求

两张方形头像,一左一右横向摆放,展示出类似PK的样式【效果图如下】

图片

分析

一看效果图我们会认为,左边的图片裁剪右下角,右边的图片裁剪左上角,然后两张图片拼接为一张就ok了,完美;但是这样一来就需要裁剪两次,合成一次,单个的展示还好,如果放到列表的cell中呢?内存不会不会一下就报表了?哈哈哈…其实,仔细分析一下,并没有那么负责,我们完全可以只切割一次就能完成:我们需要做的是让两张图片有20个像素的重叠,左边的图片正常摆放就好,右边的图片利用贝塞尔曲线重新绘制,最终显示并不需要重新合成!

ViewDidLoad
	UIView *view = [[UIView alloc]initWithFrame:CGRectMake(20, 60, _window_width-40, _window_width/2-10)];
    [self.view addSubview:view];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    [self drawBackViewWithView:view andF:NO];
    
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(20, 60 + _window_width/2, _window_width-40, _window_width/2-10)];
    [self.view addSubview:view2];
    view2.layer.cornerRadius = 10;
    view2.layer.masksToBounds = YES;
    [self drawBackViewWithView:view2 andF:YES];
- (void)drawBackViewWithView:(UIView *)view andF:(BOOL)flag{
    
  	// 左边
    UIImageView *leftIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, view.width/2+20, view.height)];
    [leftIV yb_setImageWithUrlStr:@"https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/7c910dd0-bcf2-11ea-b680-7980c8a877b8.png" placeholder:nil];
    leftIV.contentMode = UIViewContentModeScaleToFill;
    [view addSubview:leftIV];
    
    /// 右边
    UIBezierPath *rightBezier = [UIBezierPath bezierPath];
    [rightBezier moveToPoint:CGPointMake(40, 0)];
    [rightBezier addLineToPoint:CGPointMake(0, view.height)];
    [rightBezier addLineToPoint:CGPointMake(view.width, view.height)];
    [rightBezier addLineToPoint:CGPointMake(view.width, 0)];
    [rightBezier addLineToPoint:CGPointMake(40,0)];

    UIImageView *rightIV = [[UIImageView alloc]initWithFrame:CGRectMake(view.width/2-20, 0, view.width/2+20, view.height)];
    [rightIV yb_setImageWithUrlStr:@"https://main.qcloudimg.com/raw/423f07ad3f0958f61ff065c04e77afea.png" placeholder:nil complete:^(UIImage *image) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 开启位图上下文
            UIGraphicsBeginImageContextWithOptions(rightIV.frame.size, NO, 0);
            [rightBezier addClip];
            // 绘制图片
            [image drawInRect:rightIV.bounds];
            // 获取当前图片
            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            // 关闭上下文
            UIGraphicsEndImageContext();
            rightIV.image = image;
        });
    }];;
    rightIV.contentMode = UIViewContentModeScaleToFill;
    [view addSubview:rightIV];
}