我尝试如图所示在位图上写文本,但是文本质量低,我想提高文本质量,如何实现呢?
我研究了互联网,在解决方案中使用了g.drawString,但我想使用staticlayout来做到这一点。
下面将提到我使用的代码,因此我不得不说stickerview使用了此代码。
@Override
public int getWidth() {
if(!text.equals(text_origin)||isFirstGetWidth) {
text_origin = text;
isFirstGetWidth = false;
if (text.split("\n").length < 2) {
if (textPaint.measureText(text) < maxWidth) {
stickerWidth_origin = (int) textPaint.measureText(text)+ 18;
return stickerWidth_origin;
} else {
stickerWidth_origin = maxWidth+ 18;
return stickerWidth_origin;
}
}
String[] texts = text.split("\n");
stickerWidth_origin = 0;
int text_m;
for (int i = 0; i < texts.length; i++) {
if (textPaint.measureText(texts[i]) < maxWidth) {
text_m = (int) textPaint.measureText(texts[i]);
} else {
text_m = maxWidth;
}
if (text_m > stickerWidth_origin) {
stickerWidth_origin = text_m;
}
}
stickerWidth_origin = stickerWidth_origin + 18;
return stickerWidth_origin;
}
return stickerWidth_origin;
}
@Override
public int getHeight() {
if(!text.equals(text_origin)||isFirstGetHeight) {
text_origin= text;
isFirstGetHeight = false;
int lines = 0;
String[] texts = text.split("\n");
int line_m;
for (int i = 0; i < texts.length; i++) {
line_m = (int) Math.ceil(textPaint.measureText(texts[i]) / maxWidth);
if (line_m > 1) {
lines += line_m;
} else {
lines++;
}
}
if (text.endsWith("\n")) {
lines++;
}
}
return stickerHeight_origin;
}
private Bitmap Text(){
Bitmap image = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
if (drawable != null) {
drawable.setBounds(realBounds);
drawable.draw(canvas);
}
if (textRect.width() == getWidth()) {
int dy = getHeight() / 2 - staticLayoutText.getHeight() / 2;
// center vertical
canvas.translate(0, dy);
} else {
int dx = textRect.left;
int dy = textRect.top + textRect.height() / 2 - staticLayoutText.getHeight() / 2;
canvas.translate(dx, dy);
}
staticLayoutShadow.draw(canvas);
staticLayoutOutline.draw(canvas);
staticLayoutText.draw(canvas);
return image;
}
@Override
public void draw(@NonNull Canvas canvas) {
Matrix matrix = getMatrix();
canvas.save();
canvas.concat(matrix);
paint = new Paint();
paint.setAntiAlias(true);
if (mode != null)
paint.setXfermode(new PorterDuffXfermode(mode));
canvas.drawBitmap(Text(), null, realBounds, paint);
canvas.restore();
}
无论您做什么,无论何时使用画布,事物的质量都会变得模糊!但是,与其尝试在位图上绘制,不如使用具有imageview和textview的框架布局,然后捕获已加载的framelayout,大大提高您的图像质量!