开发者

UIButton location while zooming a UIScrollView

I have a "world view," so to speak, that consists of a large, zoomable area on a UIScrollView. I want several buttons to retain their world location when I pinch to zoom, much like pins in Google Maps do. The cod开发者_开发技巧e I have been trying (I have been coding for hours, but I think it sounds right...although I may be just burned out) is:

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGPoint center = button.center;
    center.y = center.y * scrollView.zoomScale;
    center.x = center.x * scrollView.zoomScale;
    button.center = center;
    NSLog(@"Button coordinates are %f, %f, zoomScale is %f", button.center.x, button.center.y, scrollView.zoomScale);
}

Can anyone see what I'm doing wrong?

Thanks in advance!


I solved this by setting the CGPoint 'center' only once, on view load, and then calculating a new center point based off of the original location.

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGPoint newCenter = center; //center is set at load time, and only once
    newCenter.y = center.y * scrollView.zoomScale; //new center is calculated on original position
    newCenter.x = center.x * scrollView.zoomScale;
    button.center = newCenter;

    NSLog(@"Button coordinates are %f, %f, zoomScale is %f", button.center.x, button.center.y, scrollView.zoomScale);
}

Sorry about mistagging the question, Peter.


You don't need to do all the maths yourself. UIScrollView's base class, UIView, has four methods for converting between coordinate systems, which in the case of a UIScrollView take zooming and panning into account:

– convertPoint:toView:
– convertPoint:fromView:
– convertRect:toView:
– convertRect:fromView:

See the UIView documentation at http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜