Drawing a target image using Cocoa Touch

Using Cocoa Touch Objective-C, I’m looking for the best way to draw the target image (i.e. the circles inside the circles are quite simple), and then the user contact is written to the image (potentially as an x ​​or + sign) and, more importantly, in memory for subsequent re-drawing.

I will use a magnifier when the user holds his finger for a long time to provide more accurate positioning, which I learned by reading and experimenting with CoffeeShopped and the source.

+8
objective-c cocoa-touch cocoa
source share
2 answers

Subclass uiview and implement drawRect

- (void)drawRect:(CGRect)rect { CGRect circleRect = self.bounds; CGFloat circleWidth = circleRect.size.width / 5.0; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); CGContextFillEllipseInRect(context, circleRect); circleRect = CGRectInset(circleRect, circleWidth, circleWidth); CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]); CGContextFillEllipseInRect(context, circleRect); circleRect = CGRectInset(circleRect, circleWidth, circleWidth); CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); CGContextFillEllipseInRect(context, circleRect); } 

Will draw

enter image description here

You must set that you look at the backgoundColor before [UIColor clearColor] to make it not black at the edges.

You can also tweak it in a loop, but this is the easiest code example I can show.

Note. I did not reuse colors, for simplicity of the arc / non-arc code

+1
source share

If you want to reuse this image and redraw it (for example, when the user touches it), you must cache this image as an image.

1) Draw your goal (as below)
2) Creating an image from the current context

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

3) Save this image and reuse it again

 - (void)drawRect:(CGRect)rect { if(image == nil) { image = [self drawTargetImage]; //use code that mentioned below to create image } [image drawAtPoint:CGPointMake(10, 10)]; } 
-one
source share

All Articles