2017-02-21 101 views
0

我想使用String创建Bitmap。问题是当我将油漆和字符串分配给Canvas。 我看到的只是一个点/黑色像素,它被创建的错误与我正在使用的配置有关? 这里是我下面的代码:使用字符串创建位图

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); 
} 

回答

0

y参数实际上是对文本的基线,这样你就不会真正看到y == 0什么。你看到的点可能是“字符串”中的“g”的下行。

尝试改用

 myCanvas.drawText("Just a string", 0, 100, paint); 

这样至少可以看到的东西。

注意:您正在根据密度设置文字大小,但是您将位图设置为绝对像素大小,因此您必须进行一些计算才能获得所需的外观。

一旦你有你Paint配置,你可以通过在Paint调用getFontMetrics(),然后看FontMetrics值确定像素文本的高度。 ascent将会是负数,因为它向上测量,所以你可以通过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);