Android 自定义ImageView 要求:imageview有最大长度和高度,按比例缩放图片
时间: 2024-04-14 19:26:39 浏览: 32
要实现这个要求,你可以自定义一个继承自 ImageView 的类,并在其中重写 onMeasure 方法来控制 ImageView 的最大长度和高度。同时,在加载图片时,你可以根据图片的宽高比例来计算缩放比例,然后使用 Matrix 对图片进行缩放操作。
下面是一个示例代码:
```java
public class CustomImageView extends ImageView {
private int mMaxWidth; // 最大宽度
private int mMaxHeight; // 最大高度
public CustomImageView(Context context) {
super(context);
init();
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置默认的最大宽度和高度
mMaxWidth = Integer.MAX_VALUE;
mMaxHeight = Integer.MAX_VALUE;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 获取 ImageView 的测量模式和尺寸
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// 计算根据最大宽度和高度得到的宽度和高度
int maxWidth = Math.min(widthSize, mMaxWidth);
int maxHeight = Math.min(heightSize, mMaxHeight);
int scaledWidth = widthSize;
int scaledHeight = heightSize;
// 根据图片的宽高比例计算缩放比例
Drawable drawable = getDrawable();
if (drawable != null) {
int imageWidth = drawable.getIntrinsicWidth();
int imageHeight = drawable.getIntrinsicHeight();
float scale = Math.min((float) maxWidth / imageWidth, (float) maxHeight / imageHeight);
scaledWidth = (int) (imageWidth * scale);
scaledHeight = (int) (imageHeight * scale);
}
// 根据测量模式设置最终的宽度和高度
int finalWidth = (widthMode == MeasureSpec.EXACTLY) ? widthSize : scaledWidth;
int finalHeight = (heightMode == MeasureSpec.EXACTLY) ? heightSize : scaledHeight;
// 设置最终的宽度和高度
setMeasuredDimension(finalWidth, finalHeight);
}
public void setMaxSize(int maxWidth, int maxHeight) {
mMaxWidth = maxWidth;
mMaxHeight = maxHeight;
}
}
```
你可以在布局文件中使用这个自定义的 ImageView,然后通过调用 `setMaxSize()` 方法来设置最大宽度和高度。当加载图片时,ImageView 会按照比例缩放图片来适应最大的宽度和高度限制。