【问题标题】:drawing with clear color on UIView (cutting a hole) in static method用静态方法在 UIView 上用清晰的颜色绘制(切一个洞)
【发布时间】:2012-06-16 08:02:48
【问题描述】:

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

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

此方法必须从UITextView 剪切(填充[UIColor clearColor])矩形r 并返回UITextView 对象。

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

怎么做?

【问题讨论】:

  • 也许我应该使用quartzcore,它是setBackground过滤器方法?

标签: iphone objective-c ios uiview core-graphics


【解决方案1】:

当你有类似的东西时:

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

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

 textView.layer

然后您可以设置一个蒙版进行剪辑。这些蒙版的工作方式如下:您通常绘制一个黑色形状,并且保持不变,其余部分将被剪裁(好吧,您实际上也可以在 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;

上面的代码也被Crop a CAShapeLayer retrieving the external path废弃了

“填充路径”部分的Quartz 2D Programming Guide 很好地解释了填充方式的原理

【讨论】:

  • 不错!请注意,对于 CGContext 执行相同操作,您添加的路径与您所做的相同,然后使用 CGContextEOFillPath(context) 填充它。 :) EO 的意思是奇数,不要与 EndOfFile 混淆(这是它为我扫描的方式)。
  • 您可以在此处使用[UIBezierPath bezierPathWithRect:biggerRect] 而不是基本的[UIBezierPath bezierPath] 来删减几行代码。这将使用预先添加的更大矩形初始化 maskPath。这样你只需要使用 moveToPoint: 和 addLineToPoint: 添加第二个矩形。
猜你喜欢
  • 2018-01-20
  • 2015-09-04
  • 1970-01-01
  • 2016-07-15
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2015-08-27
  • 2020-04-08
相关资源
最近更新 更多