android ImageView 设定宽度铺满,高度自定义
问题:imageView 宽度铺满,高度自定义,会出现上下留白的现象(一般比例的还好)
解决:
<xxx.xxx.xxx.xxx.FullWidthImageView
android:id="@+id/iv_image_corp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/pic_icon">
</cxxx.xxx.xxx.xxx.FullWidthImageView>
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.support.v7.widget.AppCompatImageView;
public class FullWidthImageView extends AppCompatImageView {
public FullWidthImageView(Context context) {
super(context);
}
public FullWidthImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FullWidthImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = Math.round((float) width / (float) drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight());
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}