创建自定义图像视图以显示比例。
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
public class ProportionalImageView extends androidx.appcompat.widget.AppCompatImageView {
public ProportionalImageView(Context context) {
super(context);
}
public ProportionalImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProportionalImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
if (d != null) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = w * d.getIntrinsicHeight() / d.getIntrinsicWidth();
setMeasuredDimension(w, h);
}
else super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
如下使用这个 ImageView
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/actionBar">
<com.dukaan.customviews.ProportionalImageView
android:id="@+id/ivBanner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
app:layout_constraintTop_toBottomOf="@id/actionBar" />
</ScrollView>
然后在设置图像之后,像往常一样,使用 Glide 或 Picasso。
我更喜欢像下面这样设置
Glide.with(context)
.load(url.equals("") ? R.drawable.task_info_image : url)
.addListener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e,
Object model, Target<Drawable> target, boolean
isFirstResource) {
dataBinding.progress.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
dataBinding.progress.setVisibility(View.GONE);
dataBinding.ivBanner.setImageDrawable(resource);
return false;
}
})
.into(dataBinding.ivBanner);
如你所愿。