ImageView.ScaleType设置图解

本文通过一个优快云博客的链接示例介绍了如何正确地分享和引用博客文章,强调了遵守网络礼仪的重要性。
http://blog.youkuaiyun.com/larryl2003/article/details/6919513
要在设置 `setScaleType(ImageView.ScaleType.MATRIX)` 后使图片显示效果不变,需要根据原本的 `scaleType` 来构建合适的 `Matrix` 对象。以下是针对不同常见 `scaleType` 的处理方式: #### 1. `CENTER` `CENTER` 类型会将图片居中显示,不进行缩放。代码示例如下: ```java ImageView imageView = findViewById(R.id.imageView); imageView.setScaleType(ImageView.ScaleType.CENTER); // 现在将 scaleType 改为 MATRIX imageView.setScaleType(ImageView.ScaleType.MATRIX); // 获取图片的宽高 Drawable drawable = imageView.getDrawable(); if (drawable != null) { int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); int viewWidth = imageView.getWidth(); int viewHeight = imageView.getHeight(); // 计算平移量 float dx = (viewWidth - drawableWidth) / 2f; float dy = (viewHeight - drawableHeight) / 2f; // 创建 Matrix 对象 Matrix matrix = new Matrix(); matrix.postTranslate(dx, dy); // 将矩阵应用到 ImageView imageView.setImageMatrix(matrix); } ``` #### 2. `CENTER_INSIDE` `CENTER_INSIDE` 会将图片完整显示在 `ImageView` 内,可能会进行等比缩放。代码示例如下: ```java ImageView imageView = findViewById(R.id.imageView); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); // 现在将 scaleType 改为 MATRIX imageView.setScaleType(ImageView.ScaleType.MATRIX); Drawable drawable = imageView.getDrawable(); if (drawable != null) { int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); int viewWidth = imageView.getWidth(); int viewHeight = imageView.getHeight(); float scale = Math.min((float) viewWidth / drawableWidth, (float) viewHeight / drawableHeight); float dx = (viewWidth - drawableWidth * scale) / 2f; float dy = (viewHeight - drawableHeight * scale) / 2f; Matrix matrix = new Matrix(); matrix.postScale(scale, scale); matrix.postTranslate(dx, dy); imageView.setImageMatrix(matrix); } ``` #### 3. `FIT_XY` `FIT_XY` 会将图片拉伸或压缩以填充整个 `ImageView`。代码示例如下: ```java ImageView imageView = findViewById(R.id.imageView); imageView.setScaleType(ImageView.ScaleType.FIT_XY); // 现在将 scaleType 改为 MATRIX imageView.setScaleType(ImageView.ScaleType.MATRIX); Drawable drawable = imageView.getDrawable(); if (drawable != null) { int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); int viewWidth = imageView.getWidth(); int viewHeight = imageView.getHeight(); float scaleX = (float) viewWidth / drawableWidth; float scaleY = (float) viewHeight / drawableHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleX, scaleY); imageView.setImageMatrix(matrix); } ``` 通过以上方法,可以在将 `scaleType` 改为 `MATRIX` 后,保持图片原本的显示效果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值