Android 使用字符串创建位图
我想使用Android 使用字符串创建位图,android,bitmap,android-bitmap,Android,Bitmap,Android Bitmap,我想使用字符串创建位图。问题是当我将绘画和字符串指定给画布时。 我所看到的只是一个点/黑像素,我使用的配置是否有问题? 下面是我的代码: private void createBitmap(){ int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getApplicationContext().getResources().getDisplayMetrics());
字符串
创建位图
。问题是当我将绘画和字符串指定给画布时。
我所看到的只是一个点/黑像素,我使用的配置是否有问题?
下面是我的代码:
private void createBitmap(){
int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getApplicationContext().getResources().getDisplayMetrics());
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(textSize);
paint.setColor(Color.BLACK);
int w = 500, h = 200;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap myBitmap = Bitmap.createBitmap(w, h, conf);
Canvas myCanvas = new Canvas(myBitmap);
myCanvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
myCanvas.drawText("Just a string", 0, 0, paint);
imageView = new ImageView(this);
imageView.setImageBitmap(myBitmap);
}
y
参数实际上是文本的基线,因此您不会看到y==0
的任何内容。你看到的点很可能是“string”中“g”的后代
试着换成
myCanvas.drawText("Just a string", 0, 100, paint);
所以至少你能看到一些东西
注意:您正在根据密度设置文本大小,但您正在将位图设置为绝对像素大小,因此必须进行一些计算才能获得所需的外观
一旦配置了Paint
,您就可以通过调用Paint
上的getFontMetrics()
,然后查看FontMetrics
值来确定文本的像素高度<代码>上升
将为负值,因为它是向上测量的,所以您可以通过fm.descent-fm.ascent
大致了解高度
以下是一种在位图上边缘下方绘制文本的方法:
Paint.FontMetrics fm = paint.getFontMetrics();
int baseline = (int) - fm.ascent; // also fm.top instead of fm.ascent
myCanvas.drawText("Just a string", 0, baseline, paint);
y
参数实际上是文本的基线,因此您不会看到y==0
的任何内容。你看到的点很可能是“string”中“g”的后代
试着换成
myCanvas.drawText("Just a string", 0, 100, paint);
所以至少你能看到一些东西
注意:您正在根据密度设置文本大小,但您正在将位图设置为绝对像素大小,因此必须进行一些计算才能获得所需的外观
一旦配置了Paint
,您就可以通过调用Paint
上的getFontMetrics()
,然后查看FontMetrics
值来确定文本的像素高度<代码>上升将为负值,因为它是向上测量的,所以您可以通过fm.descent-fm.ascent
大致了解高度
以下是一种在位图上边缘下方绘制文本的方法:
Paint.FontMetrics fm = paint.getFontMetrics();
int baseline = (int) - fm.ascent; // also fm.top instead of fm.ascent
myCanvas.drawText("Just a string", 0, baseline, paint);