Android(三十七):图片双指缩放

本文介绍了一个使用 C# 在 Android 应用中实现图片双指缩放功能的方法。通过监听 ImageView 的触摸事件,利用 MotionEvent 获取两指间的距离变化来调整图片大小,实现了放大与缩小的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

展示

在这里插入图片描述

源码

using Android.App;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;

namespace android_by_csharp
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.main);

            var avatar = FindViewById<ImageView>(Resource.Id.avatar);
            var distance = 0;
            if (avatar != null)
                avatar.Touch += (sender, args) =>
                {
                    if (args.Event == null) return;
                    // 双指按下
                    if ((args.Event.Action & MotionEventActions.Pointer2Down) == MotionEventActions.Pointer2Down)
                        distance = (int)Distance(args.Event);
                    // 双指抬起
                    else if ((args.Event.Action & MotionEventActions.Pointer2Up) == MotionEventActions.Pointer2Up)
                        Toast.MakeText(this, "双指抬起", ToastLength.Short)?.Show();

                    // 移动,双指
                    if ((args.Event.Action & MotionEventActions.Move) == 0 || args.Event.PointerCount != 2) return;
                    var moveDistance = Distance(args.Event);
                    avatar.ScaleY = avatar.ScaleX *= moveDistance / distance;

                    if (moveDistance / distance < 1)
                        Toast.MakeText(this, "缩小", ToastLength.Short)?.Show();
                    else if (moveDistance / distance > 1)
                        Toast.MakeText(this, "放大", ToastLength.Short)?.Show();
                };
        }

        // 计算两个触摸点之间的距离
        private static float Distance(MotionEvent motionEvent)
        {
            var x = motionEvent.GetX(0) - motionEvent.GetX(1);
            var y = motionEvent.GetY(0) - motionEvent.GetY(1);
            return FloatMath.Sqrt(x * x + y * y);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Prosper Lee

您的赏赐将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值