如何根据xamarin ios中的当前缩放位置缩放图像

时间:2018-04-24 05:19:23

标签: xamarin.ios uiimageview zooming

我使用UIPinchGestureRecgonizer来缩放图像。每次进行缩放时,图像都会从其中心位置而不是当前变焦位置变焦。如何基于点而不是中心来缩放图像?

UIImageView view;
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            view = new UIImageView();
            view.UserInteractionEnabled = true;
            view.Image = UIImage.FromFile("world.png");
            view.Frame = new CoreGraphics.CGRect(10, 20, 256, 256);
            UIPinchGestureRecognizer gesture = new UIPinchGestureRecognizer(pinchGesture);
            view.AddGestureRecognizer(gesture);
            View.Add(view);
            // Perform any additional setup after loading the view, typically from a nib.
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }

        private void pinchGesture(UIPinchGestureRecognizer pinchGestureRecgonizer)
        {
            pinchGestureRecgonizer.View.Transform *= CoreGraphics.CGAffineTransform.MakeScale(pinchGestureRecgonizer.Scale,
                                                                                                      pinchGestureRecgonizer.Scale);
            pinchGestureRecgonizer.Scale = 1;
        }

1 个答案:

答案 0 :(得分:0)

请参阅此文档关于AnchorPoint,我们知道更改其值以修改一个控件的转换点。由于其默认值为(0.5,0.5),因此控件将始终在中心位置缩放。

首先,让UIImageView允许多次触摸然后我们可以计算AnchorPoint。在这里,我让它成为两个手指的中心:

view.MultipleTouchEnabled = true;

// Calculate it in the touch began event
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
    base.TouchesBegan(touches, evt);

    if (touches.Count == 2)
    {
        UITouch firstTouch = touches.ToArray<UITouch>()[0];
        UITouch secondTouch = touches.ToArray<UITouch>()[1];

        var firstPoint = firstTouch.LocationInView(view);
        var secondPoint = secondTouch.LocationInView(view);

        var centerPoint = new CoreGraphics.CGPoint((firstPoint.X + secondPoint.X) / 2, (firstPoint.Y + secondPoint.Y) / 2);
        view.Layer.AnchorPoint = new CoreGraphics.CGPoint(centerPoint.X / 256, centerPoint.Y / 256);
    }
}