2013-02-26 77 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