今天的需求是 将图片按照比例 扩大至充满屏幕宽度,高度自适应
首先,后台需要返回给到图片的宽高
然后通过解析数据得到图片的宽高
假如以下是后台返回的数据 thumb_image_ext:
"thumb_image_ext": "{\"format\":\"jpeg\",\"width\":414,\"height\":714,\"colorModel\":\"ycbcr\",\"orientation\":\"Top-left\"}",
拿到数据
String imgExt = goodsInfo.thumb_image_ext;
然后需要解析他
GoodPictureSize goodPictureSize = JsonUtil.toObjectT(imgExt, GoodPictureSize.class);
其中,GoodPictureSize为一个实体类
public class GoodPictureSize implements Parcelable, HomeModel { public String format; public String width; public String height; public String colorModel; public String orientation; protected GoodPictureSize(Parcel in) { format = in.readString(); width = in.readString(); height = in.readString(); colorModel = in.readString(); } public static final Creator<GoodPictureSize> CREATOR = new Creator<GoodPictureSize>() { @Override public GoodPictureSize createFromParcel(Parcel in) { return new GoodPictureSize(in); } @Override public GoodPictureSize[] newArray(int size) { return new GoodPictureSize[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(format); parcel.writeString(width); parcel.writeString(height); parcel.writeString(colorModel); /* {"colorModel":"ycbcr","format":"jpeg","height":"712","orientation":"Top-left","width":"414"}*-**** 穿搭 {"height":"640","width":"640"}*-**** 化妆*/ } }
toObjectT() 是JsonUtil中的一个转化方法,主要将字符串对象转换为实体类型的 方法
public static <T> T toObjectT(String jsonStr, Type type) { Gson gson = new Gson(); T o = null; try { if (jsonStr != null && !"".equals(jsonStr)) { o = gson.fromJson(jsonStr, type); } } catch (Exception e) { } return o; }
引用的时候就是上面看到的那样,两个参数分别是json字符串和转化后的实体类型
GoodPictureSize goodPictureSize = JsonUtil.toObjectT(imgExt, GoodPictureSize.class);
得到之后,就可以设置图片大小,首先得到imageview这个控件 ivBiiImg
然后
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ivBiiImg.getLayoutParams(); layoutParams.height = DensityUtil.calculateHeight1(Integer.parseInt(goodPictureSize.width + ""), Integer.parseInt(goodPictureSize.height), screenWidth); layoutParams.width = Integer.valueOf(screenWidth);
其中,calculateHeight就是设置图片高度的方法
public static int calculateHeight1(int curWidth, int curHeight, int itemWidth) { float scale = (itemWidth + 0f) / curWidth; //float scale = (curWidth + 0f) / itemWidth; return (int) (curHeight * scale); }
主要实现逻辑就是
目标宽度 / 图片本身宽度 * 图片本身高度
高度直接设置为屏幕全屏宽度即可