2013-02-26 2 views
6

특정 이미지로 UIImageView 내부에 원을 그리려합니다.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 밖으로 이동하는 경우 원을 그와 함께 움직이고 싶습니다. 중요한 것은 좌표가 전체 화면에 상대적이라는 사실입니다.

+0

나에게 사용자 지정 UIView 또는 파생 된 사용자 지정 UIImageView 같은 소리. – trumpetlicks

답변

10

코어 애니메이션의 모양 레이어를 대신 사용하십시오.

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

+0

지금 어떻게 계산하고 있습니까? 동일한 기술을 사용하십시오. 그것은 동일해야합니다. 생성 한 각 원/도형 레이어에 대해 'position'속성을 설정하기 만하면됩니다. –

+0

CoordsFinal은이 방법과 독립적입니다. CGPoint – user2014474