Remove outside of bezier path
我有一个功能,我用颜色填充图像并使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 路径并填充了背景的图像。
但是,我怎样才能移除路径外的角落,或者至少获得某种方式来参考它们的位置以便我可以清除它们?
几个选项:
像你一样使用 CoreGraphics,但将其剪辑到路径:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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(); |
或者,消除CoreGraphics,只消除
1 2 3 4 5 | UIGraphicsBeginImageContextWithOptions(rect.size, false, 0); [[UIColor redColor] setFill]; [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:15.0] fill]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); |
注意,在这两个示例中,我都使用了