2013-02-26 14 views
6

Sto provando a disegnare alcuni cerchi all'interno di UIImageView con un'immagine specifica. Questo è quello che stavo cercando di fare:Disegno di una forma in 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]; 

Il cerchio è disegnato bene, ma vorrei che la PhotoView di agire come una maschera ad esso. Quindi se per esempio sposto UIImageView da UIView usando un'animazione, vorrei che il cerchio si muovesse con esso. Importante è il fatto che le coordinate sono relative all'intero schermo.

+0

Suoni come un UIView personalizzato o un UIImageView personalizzato derivato. – trumpetlicks

risposta

10

Utilizzare invece il livello di forma dell'anima core.

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

Ora, se animate l'UIImageView che contiene questo livello, il livello si sposterà con essa in quanto si tratta di un bambino strato. E ora non c'è bisogno di scavalcare lo drawRect:.

+0

sembra grandioso, ma per quanto riguarda la CoordsFinal che definisce la posizione del cerchio? – user2014474

+0

Come lo stai calcolando ora? Usa la stessa tecnica. Dovrebbe essere lo stesso. Basta impostare la proprietà 'position' per ogni livello di cerchio/forma che crei. –

+0

CoordsFinal è indipendente da questo metodo CGPoint – user2014474