4
votes

I'm trying to draw a small image on a UIScrollView for my iPhone app. I started with a UIImage created from a png I included in my bundle and that works ok. Every time the zooming/panning stops the delegate of the scrollview recalculates the frame of that UIImage (which is a subview of the UIScrollView's contentView) and calls setNeedsDisplay. The frame gets smaller and smaller in width/height measurements as you zoom into the scrollview because I want the image to stay the same size on the screen. While the user is zooming the image is the wrong size but as soon as the zooming stops it gets corrected. Not great but not the worst thing either.

The problem is now that I want to draw the image myself rather than have a static png. I've subclassed UIView and got into the drawRect method but I can't get the maths right to draw a smooth looking path when the view is zoomed in. I thought I could just scale the line width down and the radius of the circle I'm drawing (CGContextAddArc) but it looks as if the iPhone has tried to draw a thin lined circle over two or three pixels and then enlarged those pixels, rather than zoomed the view in and drawn a highly accurate circle over it.

This is the ViewController resizing the UIView (which is a subview of the UIScrollView's contentView)

float scaler = (1/scrollView.zoomScale);
[targetView setFrame:CGRectMake(viewCoords.x-11*scaler, viewCoords.y-11*scaler, 22*scaler,22*scaler)]; 
[targetView setNeedsDisplay];

This is the drawRect of the UIView

float x = rect.origin.x + rect.size.width/2.0;
float y = rect.origin.y + rect.size.height/2.0;
float radius = (rect.size.width-2.0*lineWidth)/2.0;

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx,lineWidth );

CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
CGContextAddArc(ctx, x, y, radius , 0, 2* M_PI, 1);
CGContextClosePath(ctx);
CGContextStrokePath(ctx);

I'm open to the idea of placing the UIView subclass elsewhere, but I must have it move in sync with the UIScrollView's contentview

1

1 Answers

1
votes

See my answer to this question. The UIScrollView applies a transform to your content view when it does the pinch zooming, which is what's causing your blurriness. You can override this to draw your own content sharply if you follow the method I describe.