Glide获取图片原始宽高并展示
场景需求:希望以图片的原始宽高比进行缩放,实现即使在缩略图情况下,也能看到全图。且多张图片可水平滑动。
代码:
//处理图片
private void dealWithPhoto() {
//移除布局中已存在的视图
llPhoto.removeAllViews();
for (int i = 0; i < photos.size(); i++) {
final String item = photos.get(i);
final View view = inflater.inflate(R.layout.item_order_detail_img, null, false);
final RoundedImageView rivPhoto = ViewFindUtils.find(view, R.id.rivPhoto);
final ObjectAnimator anim = ObjectAnimator.ofInt(rivPhoto, "ImageLevel", 0);
anim.setDuration(800);
anim.setRepeatCount(ObjectAnimator.INFINITE);
anim.start();
Glide.with(this).asBitmap().load(item).apply(options)
.listener(new RequestListener<Bitmap>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
anim.cancel();
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
anim.cancel();
return false;
}
})
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int width = resource.getWidth();//图片原始宽度
int height = resource.getHeight();//图片原始高度
int scaledH = UiUtils.dip2px(180f);//固定图片展示高度为180dp
int scaledW = (width * scaledH) / height;//计算出按比缩放后的宽度
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(scaledW, scaledH);
lp.setMargins(UiUtils.dip2px(5f), 0, UiUtils.dip2px(5f), 0);
rivPhoto.setLayoutParams(lp);
rivPhoto.setImageBitmap(resource);
}
});
view.setTag(R.string.position, i);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = (int) view.getTag(R.string.position);
previewPhoto(position);
}
});
llPhoto.addView(view);
}
}
布局文件item_order_detail_img.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/dialog_preview_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.makeramen.roundedimageview.RoundedImageView
android:id="@+id/rivPhoto"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:riv_corner_radius="10dp"
android:layout_gravity="center"
android:scaleType="fitCenter"/>
</LinearLayout>
父布局局部布局代码:
运行效果: