如何在Android中的Canvas文本中添加透明背景?

时间:2015-09-20 22:13:45

标签: android android-layout canvas android-bitmap

我想在价格报价上添加透明canvas。我们可以在下面的图片中看到(74美元)。我试着按照这个问题,但没有什么对我有用。这是我的code

enter image description here

@Override
public Bitmap transform(Bitmap bitmap) {
    // TODO Auto-generated method stub
    synchronized (ImageTransform.class) {
        if (bitmap == null) {
            return null;
        }
        Bitmap resultBitmap = bitmap.copy(bitmap.getConfig(), true);
        Bitmap bitmapImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_heart);
        bitmapImage = Bitmap.createScaledBitmap(bitmapImage, 50, 50, true);

        Canvas canvas = new Canvas(resultBitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(40);
        paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);
            canvas.drawText("$250", 20, 400, paint);
            canvas.drawBitmap(bitmapImage, 510, 55, null);
        bitmap.recycle();
        return resultBitmap;
    }

如何在价格部分添加透明色或图像?

修改-1

但是我可以添加画布矩形但不能在正确的位置

 Paint paintrect = new Paint();
        paintrect.setColor(Color.BLACK);
        paintrect.setStyle(Paint.Style.FILL_AND_STROKE);
        paintrect.setStrokeWidth(10);

        float left = 20;
        float top = 80;
        float right = 50;
        float bottom = 0;

        canvas.drawRect(left, top, right, bottom, paintrect);

我得到了这个: 您可以在图像的左上角看到黑色矩形。   enter image description here

1 个答案:

答案 0 :(得分:1)

你快到了!

Paint paintrect = new Paint();
    paintrect.setColor(Color.BLACK);
    paintrect.setStyle(Paint.Style.FILL_AND_STROKE);
    paintrect.setStrokeWidth(10);
    paintrect.setAlpha(127);

    float left = 18;
    float top = 360;
    float right = 128;
    float bottom = 416;

    canvas.drawRect(left, top, right, bottom, paintrect);

您必须调整矩形坐标以使其正确到达您想要的位置;我尽我所能估计。