1. 程式人生 > 實用技巧 >Android開發 Bitmap影象處理詳解

Android開發 Bitmap影象處理詳解

前言

  Bitmap開發涉及到方方面面,比如裁剪圖片,壓縮圖片,映象圖片,旋轉圖片等等,是必需掌握Android開發技巧,Android開發提供了2個類來實現這些需求,Bitmap類與BitmapFactory類。此部落格會持續更新各種實際需求。

將Res點陣圖資源轉成Bitmap

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

將Drawable向量圖資源轉成Bitmap

    public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int
drawableId) { Drawable drawable = ContextCompat.getDrawable(context, drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat) { Bitmap bitmap
= Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
else { throw new IllegalArgumentException("unsupported drawable type"); } }

映象垂直翻轉

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Matrix matrix = new Matrix();
        matrix.postScale(1, -1);   //映象垂直翻轉
        Bitmap changBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

映象水平翻轉

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1);   //映象水平翻轉
        Bitmap changBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        mBinding.weatherIcon.setImageBitmap(changBitmap);

旋轉圖片

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Matrix matrix = new Matrix();
        matrix.postRotate(-90);  //旋轉-90度
        Bitmap changBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        mBinding.weatherIcon.setImageBitmap(changBitmap);

End