Search code examples
iosobjective-ccocoa-touchuiscrollviewcore-graphics

Annotation added to UIImageView not in correct position after zooming containing UIScrollView


I have a UIScrollView. On top of it I put a UIImageView with an Image in it. Now I added another UIView on top of this UIImage view. On this UIView I d like to add some Annotations. So I d like to be able to press down one finger for 3 seconds and then there should appear some kind of an icon at the position where i pressed the finger. The Idea is that this icon shows up over the image which is set in the ImageView.

Now the problem is when I zoom the Image which has been set in UI Image View then the icon gets somehow rearranged but it doesnt stays at the position it originally was.

Example: I d like to load a picture of a bone where there is an area which might be a cancer. If I know add the annotation Icon to the position where I think there might be the cancer and rezoom the bone afterwards, the icon isnt anymore at the position where I initially marked it.

Does anyone have an idea what I have to do?

Code Extract from UIView where I d like to draw annotation icons

(void)drawRect:(CGRect)rect {
    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    //DRAW PIN IMAGE
    if(clickPosition.x > 0){
        NSLog(@"REACHED...");
        UIImage *pin = [UIImage imageNamed:@"Icon_Annotation10.png"];
        CGRect pinrect = CGRectMake(clickPosition.x, clickPosition.y, 30, 30);    
        CGContextDrawImage(contextRef, pinrect, pin.CGImage);//draws image in context
    }
}

Settings for ScrollView

// settings for scroll view
scrollView.contentSize = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height);
scrollView.maximumZoomScale = 4.0;
scrollView.minimumZoomScale = 0.75;
scrollView.clipsToBounds = YES;
scrollView.userInteractionEnabled = YES;
scrollView.delegate = self;
scrollView.scrollEnabled = NO;

Solution

  • I believe you need to multiply clickPosition.x and clickPosition.y by the scale of the zoom.

    You can get the scale by implementing the following UIScrollViewDelegate method

    - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
    

    scale in this context will be a value between the minimumZoomScale & maximumZoomScale you set.

    You then need to pass this to the view which draws the pin. The best way would probably be to have a zoomScale property on the view, and then in the delegate method above set that property to the new scale value and redraw the contents of the view.