8
votes

With Cocoa Touch in Objective-C, I'm looking for the optimal way to draw a target image, (i.e. circles within circles, simple enough), and then have the user's touch recorded on the image, (potentially as an x or + mark), and more importantly, in memory for later re-drawing.

I'll be using a loupe for when the user holds their finger down for prolonged periods to enable more precise positioning, which I've learnt by reading and experimenting with the CoffeeShopped article and source.

2

2 Answers

0
votes

Create a subclass of 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 should set you're views backgoundColor to [UIColor clearColor] to make it not black around the edges.

You could also tweak this into a loop but that is the simplest example code i can show.

Note: I've not reused the colors, for simplicity of arc/nonarc code

-1
votes

If you want to reuse that image and redraw it (for example - when user touch it) you should cache that drawing as image.

1)Draw your target (as mentioned below)
2)Create image from current context

 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

3)Save that image and next time reuse it

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