gpt4 book ai didi

带有字体的 Android Canvas 旋转文本未正确保存在 SD 卡上

转载 作者:行者123 更新时间:2023-11-30 04:00:53 24 4
gpt4 key购买 nike

我在 Canvas 上绘制旋转文本,然后将其以 JPEG 格式保存到 SD 卡。我面临的问题是 Canvas 预览看起来不错,但保存图像中的旋转文本显示不正确。当我使用默认的 Android 字体时,最终的 JPEG 与 Canvas 预览相同,但此代码不适用于自定义字体。

I have uploaded both the final saved image and screenshot of canvas preview

我正在为 Canvas 绘图使用自定义 View 类,这是我的代码

public class MyBringBack extends View {


Bitmap bitmap;
Typeface type;

public MyBringBack(Context context) {
super(context);
// TODO Auto-generated constructor stub
type = Typeface.createFromAsset(context.getAssets(),"fonts/rockwell-bold.ttf");
setDrawingCacheEnabled(true);
}


@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);



Paint paint = new Paint();
paint.setColor(Color.BLUE);
// paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
paint.setTextSize(23);
Paint paint1 = new Paint();
paint1.setTextSize(40);
paint1.setColor(Color.RED);

canvas.rotate(90,434,110);
canvas.drawText("Demo Text Demo Text Demo Text ", 434, 110, paint);
canvas.restore();
canvas.save();
paint1.setTypeface(type);
canvas.rotate(90,130,185);
canvas.drawText("Text using Typeface ", 130, 185, paint1);
canvas.restore();
canvas.save();
canvas.rotate(90,180,185);
canvas.drawText("Text using Typeface ",180, 185, paint1);
canvas.restore();
canvas.save();
canvas.rotate(90,230,185);
canvas.drawText("Text using Typeface ", 230, 185, paint1);
canvas.restore();
canvas.save();

this.setDrawingCacheEnabled(true);
Bitmap c= Bitmap.createScaledBitmap(this.getDrawingCache(), canvas.getWidth(),canvas.getHeight(), false);

/* Saving File To SD Card */

OutputStream outStream = null;
File bgv = new File("/sdcard/");
/* To build directory if needed */
bgv.mkdirs();

File file = new File(bgv, "final22.jpg");

try {
outStream = new FileOutputStream(file);
c.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

outStream.flush();
outStream.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

我的代码有问题吗?

请帮忙...

提前致谢:)

最佳答案

经过对图像处理的大量研究,我终于得到了答案。为了保存与在 Canvas 上绘制的完全相同的 jpg,我们只需添加两行代码。首先是:

setDrawingCacheQuality(DRAWING_CACHE_QUALITY_HIGH);

然后在onDraw中我们必须将AntiAlias设置为true,引用我的代码

paint1.setAntiAlias(true);

但在此之后,保存的图像与在 Canvas 上绘制的图像质量也不一样。要获得同样清晰的图像质量,这两个代码可以解决问题

paint1.setDither(true);
paint1.setFilterBitmap(true);

Dither 主要提供光滑的边角,AntiAlias、Dither 和 FilterBitmap 也可以在 Canvas 上绘制 Bitmap 时使用。

要获得更多关于 Dither 和 AntiAlias 的信息,请点击此处

AntiAlias

Dither

关于带有字体的 Android Canvas 旋转文本未正确保存在 SD 卡上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com