0

我是 iOS 开发的初学者,我正在尝试显示需要可缩放和可平移的图像(实际上是地图)。我的问题是我不知道如何添加将跟随平移以始终表示相同位置的叠加层,但不会被缩放缩放。会有多个叠加层,每个叠加层都必须是可点击的。

为了缩放和平移图像(地图),我UIImageView在 a 中添加了我的UIScrollView,效果很好,但我不知道如何添加此功能。

我找到了这个线程,但由于他的叠加层是静态的,所以这并不是同一个问题: UIScrollview with two images - Keeping 1 image zoomable and 1 image static (fixed size)

我在android中开发了相同的应用程序,为了完成这项工作,由于转换矩阵,我将地图的像素转换为屏幕坐标,并且我覆盖了onDraw方法来显示它,但我不知道如何在 iOS 上做同样的事情,我不知道这是否是更好的解决方案。

谢谢你的帮助。

4

2 回答 2

2

好的,所以我找到了一种方法,如果它可以帮助任何人:

我在滚动视图中添加了我的叠加层,带有背景图像(地图)。

+CustomScrollView
----> UIImageView (map)
----> OverlayImageView (overlay)

为了缩放,自定义滚动视图需要一个具有以下方法的委托:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    //The background image with the map
    return mapView;
}

//When a zoom occurs, move the overlay
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIImageView* overlayView = [scroll.subviews objectAtIndex:1];
    float x;
    float y;
    float width;
    float height;

    //keep the width and height of the overlay
    width = overlayView.frame.size.width;
    height = overlayView.frame.size.height;
    //Move it to stay over the same pixel of the map, and centers it
    x = (self.overlay.point.x * scroll.zoomScale - width/2);
    y = (self.overlay.point.y * scroll.zoomScale - height/2);

    overlayView.frame = CGRectMake(x,y,width,height);
} 

有了这个,我们说缩放只发生在背景图像上,但由于覆盖在 中UIScrollView,它会随之平移。所以我们唯一需要关心的是在缩放变化时移动Overlay,我们通过scrollViewDidZoom方法知道它。

为了处理触摸事件,我们覆盖了touchEnded:withEvent:of CustomScrollView,如果只有一次点击,我们将其转发到覆盖层。我没有展示,OverlayImageView因为它只覆盖这个相同的方法 ( toucheEnded:withEvent:) 来处理它的触摸。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    // Coordinates in map view
    CGPoint point = [touch locationInView:[self.subviews objectAtIndex:0]];

    //forward
    if(touch.tapCount == 1){
        OverlayImageView* overlayView = [self.subviews objectAtIndex:1];
        CGPoint newPoint = [touch locationInView:overlayView];

        BOOL isInside = [overlayView pointInside:newPoint withEvent:event];

        if(isInside){
            [overlayView touchesEnded:touches withEvent:event];
        }
    }
    // zoom
    else if(touch.tapCount == 2){


        if(self.zoomScale == self.maximumZoomScale){
            [self setZoomScale:[self minimumZoomScale] animated:YES];
        } else {
            CGRect zoomRect = [self zoomRectForScrollView:self withScale:self.maximumZoomScale withCenter:point];            

            [self zoomToRect:zoomRect animated:YES];
            //[self setZoomScale:[self maximumZoomScale] animated:YES];
        }

        [self setNeedsDisplay];

    }
}

希望这会有所帮助。

于 2012-06-27T09:58:02.763 回答
0

您可以将 imageView 作为叠加层放在顶部,并将其 userInteractionEnabled 属性设置为 NO。然后你必须以编程方式平移它。

于 2012-06-26T10:01:07.677 回答