自定义ImageView实现图片缩放动画

发布时间:2024-08-20 14:19:20 作者:小樊
来源:亿速云 阅读:83

要实现图片缩放动画,可以自定义一个ImageView,并重写其onDraw方法来实现缩放效果。以下是一个简单的示例:

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方法,在绘制图片时根据当前的缩放比例对图片进行缩放。同时提供了两个方法zoomIn和zoomOut来实现图片的放大和缩小操作。在这两个方法中,我们修改了scale的值,并调用invalidate方法来触发重绘操作。

推荐阅读:
  1. iOS中如何实现imageView任意角度旋转
  2. 详解IOS UITableViewCell 的 imageView大小更改

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

imageview

上一篇:ImageView加载过程中的动画效果

下一篇:ImageView在Android中的缓存失效处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》