简体   繁体   中英

Create Bitmap using a String

I want to create a Bitmap using the String . The problem is when I assign the Paint and String to the 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 . The dot you're seeing is probably the descender of the "g" in "string".

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. ascent will be negative since it's measuring upward, so you can get a rough idea of the height by 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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