溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

自定義ImageView實現(xiàn)圖片縮放動畫

發(fā)布時間:2024-08-20 14:19:20 來源:億速云 閱讀:83 作者:小樊 欄目:移動開發(fā)

要實現(xiàn)圖片縮放動畫,可以自定義一個ImageView,并重寫其onDraw方法來實現(xiàn)縮放效果。以下是一個簡單的示例:

public class ZoomImageView extends ImageView {

    private float scale = 1.0f;
    private Matrix matrix = new Matrix();

    public ZoomImageView(Context context) {
        super(context);
    }

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

    public ZoomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int viewWidth = getWidth();
        int viewHeight = getHeight();

        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }

        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();

        float scaleX = (float) viewWidth / drawableWidth;
        float scaleY = (float) viewHeight / drawableHeight;

        matrix.setScale(scale * scaleX, scale * scaleY);
        setImageMatrix(matrix);

        super.onDraw(canvas);
    }

    public void zoomIn() {
        if (scale < 2.0f) {
            scale *= 1.1f;
            invalidate();
        }
    }

    public void zoomOut() {
        if (scale > 0.5f) {
            scale *= 0.9f;
            invalidate();
        }
    }
}

在這個自定義的ImageView中,我們重寫了onDraw方法,在繪制圖片時根據(jù)當前的縮放比例對圖片進行縮放。同時提供了兩個方法zoomIn和zoomOut來實現(xiàn)圖片的放大和縮小操作。在這兩個方法中,我們修改了scale的值,并調(diào)用invalidate方法來觸發(fā)重繪操作。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI