2016-04-05 70 views
1

我需要將TextView轉換爲位圖。 TextView使用setAlpha()方法具有透明度。我使用下面的代碼Android視圖與透射位圖

Bitmap b = getBitmapFromView(textView , 150); 
try { 
    b.compress(Bitmap.CompressFormat.PNG, 95, new FileOutputStream(watermarkImagePath)); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 

public Bitmap getBitmapFromView(View view, int alpha) { 
    view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), 
      Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    Paint alphaPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    alphaPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); 
    alphaPaint.setColor(Color.TRANSPARENT); 
    Toast.makeText(VideoCaptureActivity.this, "alpha" + alpha, Toast.LENGTH_LONG).show(); 
    alphaPaint.setAlpha(alpha); 
    canvas.drawBitmap(bitmap,0,0,alphaPaint); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    view.draw(canvas); 
    return bitmap; 
} 

但問題是,結果圖像沒有透明度:(

+0

使用'帆布#saveLayerAlpha'之前調用'view.draw(畫布)等;' – pskink

+0

@pskink什麼應該是帆布的參數#saveLayerAlpha –

+0

HTTP:/ /developer.android.com/refer ence/android/graphics/Canvas.html#saveLayerAlpha(android.graphics.RectF,%20int,%20int) – pskink

回答

1

嘗試不同的技術是什麼爲我工作後,從視圖,完全不透明使位圖,然後設置tranparency 。中位希望這將有助於有同樣的問題

Bitmap b = addTranparencyToBitmap(getBitmapFromView(view), (int)(view.getAlpha() * 255)); 
try { 
    b.compress(Bitmap.CompressFormat.PNG, 95, new FileOutputStream(watermarkImagePath)); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 

public Bitmap getBitmapFromView(View view) { 
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), 
      Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.draw(canvas); 
    return bitmap; 
} 

public Bitmap addTranparencyToBitmap(Bitmap originalBitmap, int alpha) { 
    Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(newBitmap); 
    Paint alphaPaint = new Paint(); 
    alphaPaint.setAlpha(alpha); 
    canvas.drawBitmap(originalBitmap, 0, 0, alphaPaint); 
    return newBitmap; 
}