Android 設定圖片 Bitmap任意透明度

來源:互聯網
上載者:User

兩種思路,第一種思路是通過對Bitmap進行操作,將Bitmap的像素值get到一個int[]數組裡,因為在android裡Bitmap通常是ARGB8888格式,所以最高位就是A通道的值,對齊進行改變後再建立一個Bitmap即可。第二種思路是通過設定canvas的paint的透明度,然後通過canvas.drawBitmap()來改變View的透明度。具體代碼如下:

第一種思路:

public static Bitmap getTransparentBitmap(Bitmap sourceImg, int number){int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg.getWidth(), sourceImg.getHeight());// 獲得圖片的ARGB值number = number * 255 / 100;for (int i = 0; i < argb.length; i++) {argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF);}sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Config.ARGB_8888);return sourceImg;}

上述代碼經本人親測可用,修正了連結 的兩個錯誤。number的範圍是0-100,0表示完全透明即完全看不到。可以看到最關鍵的一步是argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF); 通過(argb[i] & 0x00FFFFFF)將第i點的像素的A通道置為0,然後和(num<<24)進行或操作。移位參見 連結

第二種思路:

範例程式碼:

    class drawCanvas extends View {        public drawCanvas(Context context) {            super(context);        }         @Override        protected void onDraw(Canvas canvas) {            super.onDraw(canvas);             // 取得Resource 圖片的Bitmap            Bitmap vBitmap = BitmapFactory.decodeResource( this.getResources()                                                         , R.drawable.icon                                                         );             // 建立Paint 物件            Paint vPaint = new Paint();            vPaint .setStyle( Paint.Style.STROKE );   //空心            vPaint .setAlpha( 75 );   //              canvas.drawBitmap ( vBitmap , 50, 100, null );  //無透明            canvas.drawBitmap ( vBitmap , 50, 200, vPaint );  //有透明        }    }

關於canvas.drawBitmap詳見 連結

兩種方法各有用途,哪個方面用哪。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.