
? ? ? ? 如圖所示,需要高度固定死,寬度需要根據(jù)比例來自適應(yīng)顯示,于是找了資料,通過自定義view實現(xiàn),重寫onMeasure方法:
public class ResizableImageView extends androidx.appcompat.widget.AppCompatImageView {
? ? public ResizableImageView(Context context) {
? ? ? ? super(context);
}
? ? public ResizableImageView(Context context, AttributeSet attrs) {
? ? ? ? super(context, attrs);
}
? ? @Override
? ? protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
? ? ? ? Drawable d = getDrawable();
? ? ? ? if (d != null) {
? ? ? ? ? ? // ceil not round - avoid thin vertical gaps along the left/right edges
? ? ? ? ? ? int width = View.MeasureSpec.getSize(widthMeasureSpec);
? ? ? ? ? ? //高度根據(jù)使得圖片的寬度充滿屏幕計算而得
? ? ? ? ? ? int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
? ? ? ? ? ? setMeasuredDimension(width, height);
? ? ? ? } else {
? ? ? ? ? ? super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}