如何将动态alpha蒙版应用于Android上的文本?

时间:2021-07-12 23:23:38

I want to make a dynamic alpha mask with drawable shapes as circles or whatever, and apply it to a drawed text on Android. Here is an example of what i want : 如何将动态alpha蒙版应用于Android上的文本?

我想做一个动态的alpha蒙版,可以绘制成圆圈或其他形状,并将它应用到Android上的绘制文本。这是我想要的一个例子:

I am trying to make it with setXfermode(new PorterDuffXfermode(Mode.SRC_IN)), but i can't get it work. Here is the code I have in onDraw(Canvas canvas) method :

我正在尝试使用setXfermode(新的PorterDuffXfermode(mod . src_in))来制作它,但是我无法让它正常工作。下面是onDraw(画布)方法中的代码:

Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.WHITE);
canvas.drawCircle(50, 50, 50, paint);

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
paint.setColor(Color.RED);
canvas.drawText("hello", 0, 50, paint);

Thanks in advance for your help

谢谢你的帮助

1 个解决方案

#1


10  

Try creating your source and mask bitmaps separately. Most of the examples I have seen involve using two bitmaps and using drawBitmap to perform the masking.

尝试分别创建源和掩码位图。我看到的大多数示例都涉及使用两个位图和使用drawBitmap来执行屏蔽。

I use PorterDuff.Mode.DST_IN for the paint, then draw the source image (with no paint) followed by the mask image (with the paint). Something like this:

我使用PorterDuff.Mode。DST_IN进行绘制,然后绘制源图像(不使用油漆),然后绘制蒙版图像(使用油漆)。是这样的:

        Bitmap bitmapOut = Bitmap.createBitmap(sizeX, sizeY,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapOut);

        Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        xferPaint.setColor(Color.BLACK);

        xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        canvas.drawBitmap(sourceImage, 0, 0, null);
        canvas.drawBitmap(alphaMask, 0, 0, xferPaint);

At this point, bitmapOut contains my masked image.

此时,bitmapOut包含我的蒙面图像。

#1


10  

Try creating your source and mask bitmaps separately. Most of the examples I have seen involve using two bitmaps and using drawBitmap to perform the masking.

尝试分别创建源和掩码位图。我看到的大多数示例都涉及使用两个位图和使用drawBitmap来执行屏蔽。

I use PorterDuff.Mode.DST_IN for the paint, then draw the source image (with no paint) followed by the mask image (with the paint). Something like this:

我使用PorterDuff.Mode。DST_IN进行绘制,然后绘制源图像(不使用油漆),然后绘制蒙版图像(使用油漆)。是这样的:

        Bitmap bitmapOut = Bitmap.createBitmap(sizeX, sizeY,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapOut);

        Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        xferPaint.setColor(Color.BLACK);

        xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        canvas.drawBitmap(sourceImage, 0, 0, null);
        canvas.drawBitmap(alphaMask, 0, 0, xferPaint);

At this point, bitmapOut contains my masked image.

此时,bitmapOut包含我的蒙面图像。