前言
安卓開發(fā)過程中梳猪,很多時候都會用到加載網(wǎng)絡圖片麻削,而加載這些網(wǎng)絡圖片往往又很占內(nèi)存,所以春弥,我們最好對這些圖片進行一個監(jiān)控呛哟。比如說,imageView的寬和高為40dp匿沛,然后經(jīng)過轉換扫责,大概是120px左右。也就是說逃呼,我們加載的圖片尺寸鳖孤,其實只要120px就行了。如果后臺返回的圖片尺寸是300px*300px抡笼,那多出的180px是沒有意義的苏揣,只會浪費內(nèi)存和流量。所以推姻,我們在開發(fā)的時候腿准,要對圖片進行一個監(jiān)控。
效果圖
如果網(wǎng)絡圖片的尺寸拾碌,大于本地imageview設置的尺寸,并且超過一定數(shù)值(比如超過100px)街望,就彈框顯示校翔,展示這張圖片,還有在哪個Activity灾前,圖片鏈接防症,網(wǎng)絡圖片和本地imageview的尺寸對比。然后再把這些信息告訴后端哎甲,讓他們下發(fā)尺寸小一點的網(wǎng)絡圖片蔫敲。
代碼實現(xiàn)
首先是建立一個統(tǒng)一加載圖片的方法,這個一般都會有:
/**
* 加載網(wǎng)絡圖片
*/
public void loadUrlImage(final Activity activity, final String url, final ImageView imageView) {
Glide.with(activity).load(url).into(imageView);
if (isShowDialog) {
checkImgSize(activity, url, imageView);
}
}
然后炭玫,就是判斷奈嘿,開發(fā)版就開啟圖片監(jiān)控:,然后去獲取網(wǎng)絡圖片的尺寸:
/**
* 獲取網(wǎng)絡圖片尺寸
*/
private void checkImgSize(final Activity activity, final String url, final ImageView imageView) {
Glide.with(activity)
.load(url)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
imageView.post(new Runnable() {
@Override
public void run() {
if (resource.getWidth() - imageView.getWidth() > imgSize || resource.getHeight() - imageView.getHeight() > imgSize) {
showDialog(activity, url, resource.getWidth(), resource.getHeight(), imageView.getWidth(), imageView.getHeight());
}
}
});
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
}
});
}
然后根據(jù)獲取的圖片尺寸和本地的進行比較吞加,如果超出了當初設置的值裙犹,那就彈框顯示:
/**
* 彈框
*/
private void showDialog(Activity activity, final String url, int urlWidth, int urlHeight, int imgWidth, int imgHeight) {
SharedPreferences sp = activity.getSharedPreferences("imgSizeSp", MODE_PRIVATE);
final SharedPreferences.Editor editor = sp.edit();
final String urls = sp.getString("img", "");
if ((dialog == null || (dialog != null && !dialog.isShowing())) && !urls.contains(url)) {
dialog = new Dialog(activity);
View view = LayoutInflater.from(activity).inflate(R.layout.show_img_size_dialog, null);
TextView textView = (TextView) view.findViewById(R.id.tv_content);
ImageView imageView = (ImageView) view.findViewById(R.id.iv_pic);
Button btn_notip = (Button) view.findViewById(R.id.btn_notip);
Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
Glide.with(activity).load(url).into(imageView);
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_notip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.putString("img", urls + url).apply();
dialog.dismiss();
}
});
textView.setText(activity.getLocalClassName() + "\n\n" + url + "\n\n" + "圖片超出View尺寸\nbitmap:" + urlWidth + " * " + urlHeight + "\nview:" + imgWidth + " * " + imgHeight);
dialog.setContentView(view);
dialog.show();
}
}
總結
思路大概就是這樣尽狠,代碼優(yōu)化就看人吧。