UIButton position while UIImage zoom on UIScrollVi

2019-05-29 09:21发布

问题:

I have a scenario where I need to implement an Offline Map concept for which I am using the image of map on a UIScrollView that zooms on PinchGesture, which works fine.

Problem

I have a UIButton on map. While zooming, the button does not track its position with respect to UIImageView which is being scaled.I am able to reframe the button without affecting its size. But the position is wrong.

TLDR, I need to reproduce the mapView with annotation kinda concept on UIScrollView with UIImage on it. Can any one help?

Thanks in advance :)

回答1:

I have found the answer for this. I initially stored the button value in a CGRect initialButtonFrame. Then I updated the button frame (only origins, not the size of the button size as I wanted the button not to zoom like the image ie; I button should not zoom) using the scrollview delegate

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
   [self manageImageOnScrollView];//here i managed the image's coordinates and zoom
   [self manageButtonCoordinatesWithRespectToImageWithScale:scale];
}

-(void)manageButtonCoordinatesWithRespectToImageWithScale:(float)scaleFactor
{

//initialButtonFrame is frame of button 
   self.button.frame = CGRectMake((initialButtonFrame.origin.x * scaleFactor),
                                  (initialButtonFrame.origin.y * scaleFactor),
                                           initialButtonFrame.size.width,
                                           initialButtonFrame.size.height);

   [self.scrollView addSubview:self.button];// I removed the button from superview while zooming and later added with updated button coordinates which I got here
 }


回答2:

If you know your current offset and zoom of your map, you should be able to compute the position of your button:

//Assuming your map image has its origin at 0, 0
CGPoint mapOffsetX, mapOffsetY; // these would come from your map as you calculated it.
CGPoint mapZoomFactor; // 1.0 means not zoomed, 3.0 means zooming in 3x, etc
CGPoint buttonAnchorPosition; //the position of your button on your map at 1.0 zoom

CGFloat buttonX = buttonAnchorPosition.x * mapZoomFactor + mapOffsetX;
CGFloat buttonY = buttonAnchorPosition.y * mapZoomFactor + mapOffsetY;

CGPoint buttonPosition = CGPointMake(buttonX, buttonY);

button.position = buttonPosition;

Try that, good luck