xcode 在 UIImageView IOS 中绘制形状

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15096063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:51:38  来源:igfitidea点击:

Drawing a shape in a UIImageView IOS

iosxcode

提问by user2014474

I am trying to draw some circles inside a UIImageView with a specific image. This is what I was trying to do:

我正在尝试在具有特定图像的 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];

The circle is drawn fine, but I would like the PhotoView to act as a mask to it. So if for example I move the UIImageView out of the UIView using an animation, I would like the circle to move with it. Important is the fact that the coordinates are relative to the whole screen.

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

回答by Matt Long

Use Core Animation's shape layer instead.

改用 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];

Now, if you animate the UIImageView that contains this layer, the layer will move with it since it is a child layer. And there is now no need to override drawRect:.

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