Drawing with clear color on a UIView (cutting a hole) in a static method

I have an iPhone app and I need to implement the following method:

+(UITextView *)textView:(UITextView *) withCuttedRect:(CGRect)r 

This method should cut (fill with [UIColor clearColor] ) rect r from UITextView and return a UITextView object.

The user will see the view behind the UITextView from the cut openings.

How can I do that?

+6
source share
1 answer

If you have something like:

  +(UITextView *)textView:(UITextView *)textView withCuttedRect:(CGRect)r { } 

you can actually just access the textview layer from the main animation with

  textView.layer 

What you can do is set the mask to trim. These masks work as follows: you usually draw a black shape, and that stays the same, the rest will be cropped (well, you can really do some things on the alpha channel, but that's something like that).

So, you need a black rectangle in the form of a mask, a rectangle in a free rectangle. for this you can roughly do

  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; 

The above code is also not used Trim CAShapeLayer extracting external path

The idea of ​​why this refueling works this way is well explained in the Quartz 2D Programming Guide in the Path Fill section.

+5
source

Source: https://habr.com/ru/post/917961/


All Articles