android " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Android ImageView 濡備綍澶勭悊澶у浘

扬州沐宇科技
2024-06-14 22:08:35
android

鍦ˋndroid涓紝澶勭悊澶у浘鐨処mageView鏈変互涓嬪嚑绉嶅父瑙佹柟娉曪細

  1. 浣跨敤BitmapFactory.Options杩涜鍥剧墖鍘嬬缉锛氬彲浠ラ€氳繃璁剧疆BitmapFactory.Options鐨刬nSampleSize灞炴€ф潵瀵瑰浘鐗囪繘琛屽帇缂╋紝浠庤€屽噺灏戝唴瀛樺崰鐢ㄣ€傝繖鏍峰彲浠ラ伩鍏峅OM锛圤ut Of Memory锛夌殑閿欒銆傜ず渚嬩唬鐮佸涓嬶細
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.large_image, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.large_image, options);

private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
  1. 浣跨敤Picasso鎴朑lide绛夊浘鐗囧姞杞藉簱锛氳繖浜涘浘鐗囧姞杞藉簱鍙互甯姪澶勭悊澶у浘鐨勫姞杞藉拰灞曠ず锛岃嚜鍔ㄨ繘琛屽帇缂╁拰缂撳瓨锛屽噺灏戝簲鐢ㄧ殑鍐呭瓨鍗犵敤銆傜ず渚嬩唬鐮佸涓嬶細

浣跨敤Picasso鍔犺浇鍥剧墖锛?/p>

Picasso.with(context)
    .load(R.drawable.large_image)
    .resize(100, 100)
    .centerCrop()
    .into(imageView);

浣跨敤Glide鍔犺浇鍥剧墖锛?/p>

Glide.with(context)
    .load(R.drawable.large_image)
    .override(100, 100)
    .into(imageView);
  1. 浣跨敤鑷畾涔夌殑缂╂斁ImageView锛氬彲浠ラ€氳繃鑷畾涔塈mageView鏉ュ疄鐜板浘鐗囩殑缂╂斁鍜屽睍绀猴紝鏍规嵁闇€瑕佸姩鎬佽皟鏁村浘鐗囩殑澶у皬鍜屾樉绀烘晥鏋溿€傜ず渚嬩唬鐮佸涓嬶細
public class ScalableImageView extends ImageView {
    public ScalableImageView(Context context) {
        super(context);
    }

    public ScalableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScalableImageView(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 = width * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

浠ヤ笂鏄鐞嗗ぇ鍥剧殑鍑犵甯歌鏂规硶锛屽紑鍙戣€呭彲浠ユ牴鎹叿浣撻渶姹傞€夋嫨鍚堥€傜殑鏂规硶鏉ュ鐞嗗ぇ鍥剧殑ImageView銆?/p>

扫码添加客服微信