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方法触发重新绘制。

相关内容

热门资讯

透视神器!微乐小程序免费黑科技... 透视神器!微乐小程序免费黑科技,微乐南昌辅助神器(透视)本来有辅助软件(哔哩哔哩)1、免费脚本咨询教...
透视机巧!wpk辅助购买(AA... 透视机巧!wpk辅助购买(AApoker ai插件)果然存在有辅助app(哔哩哔哩);1、金币登录送...
黑科技插件!微乐小程序黑科技免... 黑科技插件!微乐小程序黑科技免费,微乐游戏竞技团辅助(透视)竟然是真的辅助方法(哔哩哔哩)所有人都在...
透视攻略!wpk德州局透视(德... 透视攻略!wpk德州局透视(德普之星透视)好像有辅助软件(哔哩哔哩)一、wpk德州局透视游戏安装教程...
透视黑科技!微乐小程序黑科技免... 透视黑科技!微乐小程序黑科技免费,微乐自建房免费黑科技下载(透视)真是存在有辅助插件(哔哩哔哩)1、...
透视窍门!hhpoker透视工... 透视窍门!hhpoker透视工具(德普之星埋牌)确实是真的有辅助脚本(哔哩哔哩)1、这是跨平台的hh...
透视新版!微乐小程序黑科技免费... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视妙计!wejoker透视方... 透视妙计!wejoker透视方法(AApoker辅助器)一直有辅助技巧(哔哩哔哩)wejoker透视...
明白辅助挂!微乐小程序免费黑科... 明白辅助挂!微乐小程序免费黑科技,微信小程序微乐破解器(透视)确实是有辅助器(哔哩哔哩)1、上手简单...
透视好友房!微乐小程序黑科技,... 透视好友房!微乐小程序黑科技,广西微乐小程序微信辅助器免费(透视)竟然是真的辅助工具(哔哩哔哩)1、...