Android放大和缩小图片
创始人
2024-10-07 18:01:05
0

要在Android中放大或缩小图片,可以使用Matrix类来进行图像变换。以下是一个示例代码,演示如何使用Matrix来放大和缩小图片。

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;

public class ZoomableImageView extends ImageView {

    private Matrix matrix;
    private float scale = 1f;
    private ScaleGestureDetector scaleGestureDetector;

    public ZoomableImageView(Context context) {
        super(context);
        init(context);
    }

    public ZoomableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        matrix = new Matrix();
        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
    }

    @Override
    protected void onDraw(android.graphics.Canvas canvas) {
        // Apply the scale transformation to the matrix
        matrix.setScale(scale, scale);
        setImageMatrix(matrix);

        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Pass touch events to the scale gesture detector
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // Get the scale factor from the detector
            float scaleFactor = detector.getScaleFactor();

            // Apply the scale factor to the current scale
            scale *= scaleFactor;

            // Limit the scale within certain bounds if needed
            scale = Math.max(0.1f, Math.min(scale, 5.0f));

            // Invalidate the view to trigger a redraw
            invalidate();

            return true;
        }
    }
}

要使用这个自定义的ZoomableImageView,只需在布局文件中将ImageView替换为ZoomableImageView


在这个示例中,我们使用ScaleGestureDetector来检测放大和缩小手势。在onScale方法中,我们通过获取缩放因素来调整图像的缩放比例,然后使用invalidate方法触发重新绘制。

相关内容

热门资讯

透视系统"wepok... 透视系统"wepokerplus透视脚本免费"详细辅助可靠技巧(总是是有挂);人气非常高,ai更新快...
透视游戏"约局吧ap... 透视游戏"约局吧app有挂吗"详细辅助解说技巧(一直真的是有挂)1、玩家可以在约局吧app有挂吗软件...
透视挂"werpla... 透视挂"werplan透视挂"详细辅助透明挂教程(原本有挂)是由北京得werplan透视挂黑科技有限...
透视规律"aapok... 透视规律"aapoker辅助工具安全吗"详细辅助必胜教程(一贯是真的有挂);建议优先通过aapoke...
透视辅助"hhpok... 透视辅助"hhpoker免费透视脚本"详细辅助辅助教程(原生有挂);大神普及一款德州ai内幕,确定了...
透视安卓版"wepo... 透视安卓版"wepoker辅助器安装包"详细辅助解密教程(好像真的有挂);玩家必备必赢加哟《1367...
透视规律"wepok... 1、透视规律"wepoker作弊方法"详细辅助安装教程(从来存在有挂)2、进入游戏-大厅左侧-新手福...
透视ai"poker... 您好,pokermaster破解版这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
透视规律"约局吧德州... 透视规律"约局吧德州透视"详细辅助2025新版教程(起初真的有挂);《WPK辅助透视》‌:支持手机实...
透视了解"微扑克微乐... 透视了解"微扑克微乐辅助"详细辅助微扑克教程(竟然真的有挂);玩家必备必赢加哟《136704302》...