移除bezier路径

时间:2017-06-11 20:35:42

标签: ios objective-c core-graphics uibezierpath

我有一个功能,我用一种颜色填充图像,然后使用UIBezierPath擦除角点。

CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetBlendMode(context, kCGBlendModeCopy);

// Fill image
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);

// Round corners
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:15.0];
CGContextSetStrokeColorWithColor(context, [[UIColor clearColor] CGColor]);
[bezierPath stroke];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

通过上面的描述,我得到的图像确实切掉了Bézier路径,并填充了背景。 Icon with Bézier path cut out

但是,如何删除路径外的角落,或至少以某种方式引用它们的位置,以便我可以清除它们?

1 个答案:

答案 0 :(得分:2)

有两种选择:

  1. 像你一样使用CoreGraphics,但将其剪辑到路径:

    CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
    
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    
    // Round corners
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:15.0];
    CGContextAddPath(context, bezierPath.CGPath);
    CGContextClip(context);
    
    // Fill image
    CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
  2. 或者,取消CoreGraphics并fill UIBezierPath

    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0);
    [[UIColor redColor] setFill];
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:15.0] fill];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
  3. 注意,在这两个示例中,我使用了UIGraphicsBeginImageContextWithOptions,提供了0的比例(针对相关设备上的显示进行了优化的比例)。如果你真的想要,你可以提供1的比例,当在视网膜设备上呈现时显然会有点像素化,但这取决于你。

相关问题