用静态方法在UIView(切孔)上绘制清晰的颜色

use*_*666 6 iphone core-graphics objective-c uiview ios

我有一个iPhone应用程序,我需要实现以下方法:

+(UITextView *)textView:(UITextView *) withCuttedRect:(CGRect)r
Run Code Online (Sandbox Code Playgroud)

此方法必须从中删除(填充[UIColor clearColor])rect 并返回对象.rUITextViewUITextView

用户将从UITextView切割孔看到后面的视图.

怎么做到呢?

小智 6

当你有类似的东西时:

 +(UITextView *)textView:(UITextView *)textView withCuttedRect:(CGRect)r {
}
Run Code Online (Sandbox Code Playgroud)

你实际上可以简单地从核心动画中访问textview的图层

 textView.layer
Run Code Online (Sandbox Code Playgroud)

然后你可以设置一个剪裁掩码.这些掩码的工作方式如下:你通常画一个黑色的形状,并保持不变,其余部分将被剪裁(好吧,你实际上也可以在alpha通道上做一些事情,但大致就是这样).

因此,您需要一个黑色矩形作为蒙版,矩形内的矩形是免费的.为此,你可以大约做

 CAShapeLayer *mask = [[CAShapeLayer alloc] init];
 mask.frame = self.textView.layer.bounds;
 CGRect biggerRect = CGRectMake(mask.frame.origin.x, mask.frame.origin.y, mask.frame.size.width, mask.frame.size.height);
 CGRect smallerRect = CGRectMake(50.0f, 50.0f, 10.0f, 10.0f);

 UIBezierPath *maskPath = [UIBezierPath bezierPath];
[maskPath moveToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMaxY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(biggerRect), CGRectGetMinY(biggerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(biggerRect), CGRectGetMinY(biggerRect))];

[maskPath moveToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMaxY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMaxX(smallerRect), CGRectGetMinY(smallerRect))];
[maskPath addLineToPoint:CGPointMake(CGRectGetMinX(smallerRect), CGRectGetMinY(smallerRect))];

 mask.path = maskPath.CGPath;
[mask setFillRule:kCAFillRuleEvenOdd];
 mask.fillColor = [[UIColor blackColor] CGColor];
 self.textView.layer.mask = mask;
Run Code Online (Sandbox Code Playgroud)

上面的代码也被Crop a CAShapeLayer检索外部路径所废弃

Quartz 2D Programming Guide的"填充路径"一节中很好地解释了为什么填充这种方式的想法.