Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text cutout in bitmap for Android

I want to achieve the following effect in Android: https://i.sstatic.net/owulU.png

I am pretty close using the method below, but I now need it to clear the background while the text still is there. The overlay text also has a light tint – because of #setColor(Color.WHITE) – but without it no text is shown.

public static Bitmap filterTextLetters(Bitmap bitmap, String text) {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.WHITE);
    paint.setTextAlign(Align.CENTER);
    paint.setTypeface(Typeface.DEFAULT_BOLD);
    paint.setTextSize(180);
    paint.setXfermode(new PixelXorXfermode(Color.BLACK));

    Bitmap photo = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    Canvas canvas = new Canvas(photo);

    canvas.drawText(text, Statics.PHOTO_WIDTH / 2, Statics.PHOTO_HEIGHT / 2, paint);

    return photo;
}
like image 456
n83 Avatar asked Aug 11 '26 22:08

n83


1 Answers

You can use a BitmapShader:

public static Bitmap filterTextLetters(Bitmap bitmap, String text) {
  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  paint.setTextAlign(Align.CENTER);
  paint.setTypeface(Typeface.DEFAULT_BOLD);
  paint.setTextSize(180);

  Shader shader = new BitmapShader(
      bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
  paint.setShader(shader);

  final int width = bitmap.getWidth();
  final int height = bitmap.getHeight();
  Bitmap photo = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(photo);
  canvas.drawText(text, width / 2, height / 2, paint);

  return photo;
}
like image 155
chiuki Avatar answered Aug 13 '26 11:08

chiuki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!