2013-02-26 49 views
6

我想用一个特定的图像在UIImageView中绘制一些圆圈。这就是我要怎样做:在UIImageView中绘制形状IOS

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,我希望圆圈随之移动。重要的是坐标是相对于整个屏幕的事实。

+0

听起来像一个自定义的UIView或派生自定义UIImageView给我。 – trumpetlicks 2013-02-26 18:06:19

回答

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:

+0

似乎很棒,但是设置圈子位置的CoordsFinal呢? – user2014474 2013-02-26 18:29:34

+0

你现在怎么计算它?使用相同的技术。它应该是一样的。只需为您创建的每个圆形/形状图层设置'position'属性即可。 – 2013-02-26 18:34:21

+0

CoordsFinal是一个独立于这种方法的CGPoint – user2014474 2013-02-26 18:55:07