6

我正在尝试使用特定图像在 UIImageView 内绘制一些圆圈。这就是我想要做的:

UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(contextRef, 2.0);
CGContextSetStrokeColorWithColor(contextRef, [color CGColor]);
CGRect circlePoint = (CGRectMake(coordsFinal.x, coordsFinal.y, 50.0, 50.0));

CGContextStrokeEllipseInRect(contextRef, circlePoint);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[photoView addSubview:image];

圆圈画得很好,但我希望 PhotoView 充当它的面具。因此,例如,如果我使用动画将 UIImageView 移出 UIView,我希望圆圈随之移动。重要的是坐标是相对于整个屏幕的事实。

4

1 回答 1

10

改用 Core Animation 的形状层。

CAShapeLayer *circleLayer = [CAShapeLayer layer];
// Give the layer the same bounds as your image view
[circleLayer setBounds:CGRectMake(0.0f, 0.0f, [photoView bounds].size.width, 
                                              [photoView bounds].size.height)];
// Position the circle anywhere you like, but this will center it
// In the parent layer, which will be your image view's root layer
[circleLayer setPosition:CGPointMake([photoView bounds].size.width/2.0f, 
                                    [photoView bounds].size.height/2.0f)];
// Create a circle path.
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:
                                    CGRectMake(0.0f, 0.0f, 50.0f, 50.0f)];
// Set the path on the layer
[circleLayer setPath:[path CGPath]];
// Set the stroke color
[circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
// Set the stroke line width
[circleLayer setLineWidth:2.0f];

// Add the sublayer to the image view's layer tree
[[photoView layer] addSublayer:circleLayer];

现在,如果您为包含此图层的 UIImageView 设置动画,该图层将随之移动,因为它是一个子图层。现在不需要覆盖drawRect:.

于 2013-02-26T18:24:49.327 回答