zoukankan      html  css  js  c++  java
  • 每日博客

    Android 中 Bitmap 和 Drawable 相互转换的方法

    Drawable 转换成 Bitmap

    1.通过 BitmapFactory 中的 decodeResource 方法,将资源文件中的 R.drawable.ic_drawable 转化成Bitmap

    Resources res = getResources();
    Bitmap    bmp = BitmapFactory.decodeResource(res, R.drawable.ic_drawable);

    2.将 Drable 对象先转化成 BitmapDrawable ,然后调用 getBitmap 方法 获取

    Resource res      = gerResource();
    Drawable drawable = res.getDrawable(R.drawable.ic_drawable);//获取drawable
    BitmapDrawable bd = (BitmapDrawable) drawable;
    Bitmap bm         = bd.getBitmap();

    3.根据已有的Drawable创建一个新的Bitmap

    public static Bitmap drawableToBitmap(Drawable drawable) {
    
            int w = drawable.getIntrinsicWidth();
            int h = drawable.getIntrinsicHeight();
            System.out.println("Drawable转Bitmap");
            Bitmap.Config config =
                    drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                            : Bitmap.Config.RGB_565;
            Bitmap bitmap = Bitmap.createBitmap(w, h, config);
            //注意,下面三行代码要用到,否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, w, h);
            drawable.draw(canvas);
    
            return bitmap;
        }

    Bitmap 转换成 Drawable

    Drawable drawable = new BitmapDrawable(bmp);
  • 相关阅读:
    297. Serialize and Deserialize Binary Tree
    331. Verify Preorder Serialization of a Binary Tree
    332. Reconstruct Itinerary
    329. Longest Increasing Path in a Matrix
    319. Bulb Switcher
    292. Nim Game
    299. Bulls and Cows
    Ice Cream Tower Gym
    B
    C
  • 原文地址:https://www.cnblogs.com/hfy717/p/14904888.html
Copyright © 2011-2022 走看看