我创建了一个固定图像比率的ImageView。因此我需要android.widget.ImageView#getMaxWidth
。通过将我的代码转换为Android 10兼容,我无法使用此功能。什么是解决图像视图的最大宽度/高度的解决方法?
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w, h;
if (getDrawable() == null) {
w = h = 0;
} else {
w = getDrawable().getIntrinsicWidth();
h = getDrawable().getIntrinsicHeight();
}
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
int wPadding = getPaddingLeft() + getPaddingRight();
int hPadding = getPaddingTop() + getPaddingBottom();
int widthSize = resolveAdjustedSize(w + wPadding, getMaxWidth(), widthMeasureSpec);
int heightSize = resolveAdjustedSize(h + hPadding, getMaxHeight(), heightMeasureSpec);
float actualRatio = (float) (widthSize - wPadding) / (heightSize - hPadding);
if (Math.abs(actualRatio - ratio) > 0.0000001) {
boolean done = false;
if (resizeWidth) {
int newWidth = (int) ((heightSize - hPadding) / ratio) + wPadding;
widthSize = resolveAdjustedSize(newWidth, getMaxWidth(), widthMeasureSpec);
} else if (!done && resizeHeight) {
int newHeight = (int) ((widthSize - wPadding) * ratio) + hPadding;
heightSize = resolveAdjustedSize(newHeight, getMaxHeight(), heightMeasureSpec);
}
}
setMeasuredDimension(widthSize, heightSize);
}
答案 0 :(得分:1)
好的,这就是我做的。为了跟踪图像的最大宽度/高度,我覆盖了属性的setter。只有setter用于编写这些属性。
private int mMaxWidth = Integer.MAX_VALUE;
private int mMaxHeight = Integer.MAX_VALUE;
@Override
public void setMaxHeight(int maxHeight) {
mMaxHeight = maxHeight;
super.setMaxHeight(maxHeight);
}
@Override
public void setMaxWidth(int maxWidth) {
mMaxWidth = maxWidth;
super.setMaxWidth(maxWidth);
}