如何使图像视图支持缩放,平移手势

时间:2020-04-16 10:13:09

标签: java android

这是我的第一个草稿代码,我想我的代码差不多完成了,只是有点奇怪,当我拖动时,我的触摸动作不是图像移动,因此如何解决

enter image description here

public class ZoomPanImageView extends View {
    Context ctx;
    Bitmap bm;

    public ZoomPanImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        ctx = context;
        bm = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.sample);
        final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(ctx, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
            @Override
            public boolean onScale(ScaleGestureDetector detector) {
                pan(detector.getScaleFactor());
                return super.onScale(detector);
            }
        });
        setOnTouchListener(new OnTouchListener() {
            float startX;
            float startY;

            @Override
            public boolean onTouch(View v, MotionEvent ev) {
                scaleDetector.onTouchEvent(ev);
                int act = ev.getAction();
                if (act == MotionEvent.ACTION_DOWN) {
                    startX = ev.getX();
                    startY = ev.getY();
                } else {
                    float dx = ev.getX() - startX;
                    float dy = ev.getY() - startY;
                    zoom(dx, dy);
                }
                // return true make sure ACTION_MOVE work
                return true;
            }
        });
    }

    void pan(float scaleFactor) {
        scale = scale * scaleFactor;
        redraw();
    }

    void zoom(float dx, float dy) {
        translateX += dx;
        translateY += dy;
        redraw();
    }

    void redraw() {
        invalidate();
    }

    float scale = 1;
    float translateX;
    float translateY;
    boolean inited = false;
    float cw;
    float ch;
    Canvas canvas;

    @Override
    protected void onDraw(Canvas canvas) {
        this.canvas = canvas;
        cw = canvas.getWidth();
        ch = canvas.getHeight();
        if (!inited) {
            if (bm != null) {
                getBestFit();
                inited = true;
            }
        } else {
            drawImg();
        }
    }

    void getBestFit() {
        int imgW = bm.getWidth();
        int imgH = bm.getHeight();
        if (imgW * 1f / imgH > cw * 1f / ch) {
            scale = ch * 1f / imgH;
        } else {
            scale = cw * 1f / imgW;
        }

        translateX = (int) ((cw - imgW * scale) / 2);
        translateY = (int) ((ch - imgH * scale) / 2);

        drawImg();
    }

    private void drawImg() {
        canvas.translate(translateX, translateY);
        canvas.scale(scale, scale);
        canvas.drawBitmap(bm, 0, 0, null);
    }
}

0 个答案:

没有答案