使用String创建位图

时间:2017-02-21 18:32:03

标签: android bitmap android-bitmap

我想使用Bitmap创建String。问题是当我将Paint和String分配给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);
}

1 个答案:

答案 0 :(得分:0)

y参数实际上是文本的基线,因此您不会真正看到y == 0的任何内容。你看到的点可能是“字符串”中“g”的下降。

尝试更改为

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

所以至少你可以看到一些东西。

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

配置好Paint后,您可以通过调用getFontMetrics()上的Paint,然后查看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);