在Xcode/objective-c中,将图像绘制到两个同心圆之间的区域



我有一个图像(实际上是圆形的),只想画出该图像中与两个同心圆之间的区域相对应的部分,外部的是固定的,内部的可以调整大小。

外部同心圆将始终与图像的外部边缘相对应,但需要在绘制的图像中留下一个"洞",与较小同心圆的大小相对应。

我尝试在objective-c for iOS中这样做——绘制一个可变大小的"取景器"控件。

非常感谢您的帮助。

听起来像是使用CGContextEOClip的标准情况。尚未检查此代码,但类似于:

CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, outerCircle);
CGPathAddEllipseInRect(path, NULL, innerCircle);
CGContextEOClip(ctxt);
//Draw your stuff

最简单、性能最好的解决方案可能是使用UIImageView并应用CAShapeLayer作为其层的掩码。

示例:

UIImage *image = ...;
CGFloat ringWidth = 20.0;
CGRect outerCircleRect = CGRectMake(0, 0, image.size.width, image.size.height);
CGRect innerCircleRect = CGRectInset(outerCircleRect, ringWidth, ringWidth);
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:outerCircleRect];
[path appendPath:[UIBezierPath bezierPathWithOvalInRect:innerCircleRect]];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.fillRule = kCAFillRuleEvenOdd;
shapeLayer.path = [path CGPath];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
imageView.layer.mask = shapeLayer;
[self.view addSubview:imageView];

您必须包含QuartzCore框架才能工作。

更改内圈的半径时,只需为造型图层指定一条新路径即可。这甚至可以设置动画。

最新更新