Skip to content

Instantly share code, notes, and snippets.

@CoderChoy
Created June 9, 2017 02:59
Show Gist options
  • Save CoderChoy/1f77c07cdee586c1ee06db4cc1c19141 to your computer and use it in GitHub Desktop.
Save CoderChoy/1f77c07cdee586c1ee06db4cc1c19141 to your computer and use it in GitHub Desktop.
在bitmap上打印文字(居中)
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
public class Utils {
public static Bitmap drawTextToBitmap(String text) {
Bitmap bitmap = Bitmap.createBitmap(360, 130, Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setTextSize(120);
paint.setFakeBoldText(true);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x1 = (bitmap.getWidth() - bounds.width()) / 2;
int y1 = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(text, x1, y1, paint);
//上面代码已完成在bitmap上打印文字(居中),下面是把bitmap转成黑白图
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height); //取得BITMAP的所有像素点
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = pixels[offset + x] != 0 ? 0xFF000000 : 0xFFFFFFFF;
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment