位图未正确保存(从Android的画布)
我稍微改变了我的问题 编辑:位图未正确保存(从Android的画布),android,opengl-es,canvas,fonts,bitmap,Android,Opengl Es,Canvas,Fonts,Bitmap,我稍微改变了我的问题 编辑: // make textures from text public static void createTextureFromText(GL10 gl, String text, String texName) { Paint p = new Paint(); p.setColor(Color.GREEN); p.setTextSize(32 * getResources().getDisplayMetrics().density);
// make textures from text
public static void createTextureFromText(GL10 gl, String text, String texName) {
Paint p = new Paint();
p.setColor(Color.GREEN);
p.setTextSize(32 * getResources().getDisplayMetrics().density);
// get width and height the text takes (in px)
int width = (int) p.measureText(text);
int height = (int) p.descent();
// Create an empty, mutable bitmap based on textsize
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bmp);
bmp.eraseColor(Color.CYAN); //Cyan for debugging purposes
//draw the text
canvas.drawText(text, 0, 0, p);
// save image - for debugging purposes
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// create a new file name "test.jpg" in sdcard
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
try {
f.createNewFile();
// write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
.... make texture
}
我现在有了这段代码,用于从给定文本创建纹理(这只是部分内容)。
但是我发现错误在位图创建的某个地方。现在,我将位图保存在sd卡上,看看结果如何,并发现我得到了一个全青色位图(672B、164x7是尺寸)
有人知道为什么它不创建带有文本的位图吗?我会做错什么
如果你能帮助我,你将是一个英雄:)首先,你的文字高度计算是错误的。“下降”测量值仅为基线下方的文本部分(即“g”和“q”等的尾部)。正确的高度为上升+下降,但由于上升为负值,您需要:
int height = (int) (p.descent() + -p.ascent());
其次,当您drawText()时,您给它的y坐标是基线的位置,而不是上边缘或下边缘。因此,如果你想填充一个刚好能容纳文本的位图,你的y坐标也应该是
-p.ascent()
我不知道这是否是一个好的解决方案,但是如果你用文本创建一个文本视图(不在屏幕上显示),你可以测量这个视图,使用这些尺寸创建位图,然后使用它在使用位图创建的画布上绘制(textview.draw(canvas))。最终会得到与文本完全匹配的位图。我不知道这会有多有效。textview将适应您拥有的任何字体大小/间距,因此它可以工作…-->说“用指定的颜色填充位图的像素。”太棒了!这让我耽搁了一个多星期,你帮我解决了这个问题:D显然我只需要知道这些方法的正确含义。谢谢