Android视图到透明的位图

时间:2016-04-05 08:22:34

标签: android bitmap png

我需要将TextView转换为位图。 TextView使用setAlpha()方法具有透明性。我正在使用以下代码

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;
}

但问题是结果图片没有透明度:(

1 个答案:

答案 0 :(得分:1)

尝试不同的技术后,对我来说有用的是从视图中创建具有完全不透明度的位图,然后设置位图的透明度。希望它能帮助其他人有同样的问题

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;
}