UIBezierPath+CAShapeLayer繪製微信聊天圖片效果

benlue發表於2019-01-17
CGRect rect = CGRectMake(100, 100, 150, 250);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
    imageView.image = [UIImage imageNamed:@"brand_launch"];
    
    [self.view addSubview:imageView];
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    //起點
    [path moveToPoint:CGPointMake(0, 15)];
    //路徑點
    [path addLineToPoint:CGPointMake(15, 15)];
    //第一個圓角點 x=尖角寬+圓角半徑 y=圓角半徑
    [path addArcWithCenter:CGPointMake(15+5, 5) radius:5 startAngle:M_PI endAngle:1.5*M_PI clockwise:YES];
    //第二個圓角點 x=view寬-圓角半徑 y=圓角半徑
    [path addArcWithCenter:CGPointMake(150-5, 5) radius:5 startAngle:1.5*M_PI endAngle:2*M_PI clockwise:YES];
    //第三個圓角點 x=view寬-圓角半徑 y=view高-圓角半徑
    [path addArcWithCenter:CGPointMake(150-5, 250-5) radius:5 startAngle:0 endAngle:M_PI_2 clockwise:YES];
    //第四個圓角點 x=尖角寬+圓角半徑 y=view高-圓角半徑
    [path addArcWithCenter:CGPointMake(15+5, 250-5) radius:5 startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
    [path addLineToPoint:CGPointMake(15, 30)];
    [path closePath];//閉合路徑
    
    layer.path = path.CGPath;
    
    imageView.layer.mask = layer;

複製程式碼
"思路: 如果想應用在多種圖片格式上? "

我可能會考慮把這個圓角放到一個UIView上,
然後通過重寫ViewLayoutSubviews方法來實時取到正確的view的寬高, 來實現繪製 

各人按需求封裝一下吧

複製程式碼

相關文章