简体   繁体   English

使用String创建位图

[英]Create Bitmap using a String

I want to create a Bitmap using the String . 我想使用String创建一个Bitmap The problem is when I assign the Paint and String to the Canvas . 问题是当我将Paint和String分配给Canvas All I see is a dot/black pixel that is created is something wrong with the Configs that I am using? 所有我看到的是创建的点/黑色像素是我使用的配置有问题吗? Here is my code below: 这是我的代码如下:

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

The y parameter is actually for the baseline of the text, so you won't really see anything with y == 0 . y参数实际上是文本的基线,因此您不会真正看到y == 0任何内容。 The dot you're seeing is probably the descender of the "g" in "string". 你看到的点可能是“字符串”中“g”的下降。

Try changing to 尝试改为

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

so at least you can see something. 所以至少你可以看到一些东西。

Note: You are setting the text size based on density, but you are making the bitmap an absolute pixel size, so you are going to have to do some calculation to get the look you want. 注意:您正在根据密度设置文本大小,但是您要使位图成为绝对像素大小,因此您将不得不进行一些计算以获得所需的外观。

Once you have your Paint configured, you can determine the height of the text in pixels by calling getFontMetrics() on the Paint , then looking at the FontMetrics values. 配置完Paint ,可以通过在Paint上调用getFontMetrics() ,然后查看FontMetrics值来确定文本的高度(以像素为getFontMetrics() ascent will be negative since it's measuring upward, so you can get a rough idea of the height by fm.descent - fm.ascent . ascent将是负面的,因为它向上测量,所以你可以通过fm.descent - fm.ascent大致了解高度。

Here's a way to draw your text just below the top edge of the bitmap: 这是一种在位图顶部边缘下方绘制文本的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM