【问题标题】:Adding text to a bitmap with canvas使用画布将文本添加到位图
【发布时间】:2014-11-07 04:49:34
【问题描述】:

我有一些将文本添加到位图中的代码。除非文本比原始图像宽,否则这种方法效果很好。

如何使图像足够宽以使我的文本正确显示?

这是我的代码:

private BitmapDescriptor GetCustomBitmapDescriptor(string text)
{
    Bitmap baseBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon);
    Bitmap bitmap = baseBitmap.Copy(Bitmap.Config.Argb8888, true);
    Paint paint = new Paint(PaintFlags.AntiAlias);
    Rect bounds = new Rect();

    paint.GetTextBounds(text, 0, text.Length, bounds);

    float bitmapMiddle = bitmap.Width / 2.0f;

    Canvas canvas = new Canvas(bitmap);

    canvas.DrawText(text, bitmapMiddle - (bounds.Right / 2.0f), bitmap.Height, paint);

    BitmapDescriptor icon = BitmapDescriptorFactory.FromBitmap(bitmap);

    return (icon);
}

提前致谢。

【问题讨论】:

    标签: c# android canvas text bitmap


    【解决方案1】:

    只需颜色代码,它就可以工作

    私有位图 GetCustomBitmapDescriptor(String text) { 位图 baseBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launche); 位图 bitmap = baseBitmap.copy(Bitmap.Config.ARGB_8888, true); 油漆油漆=新油漆(油漆.ANTI_ALIAS_FLAG); 矩形边界 = new Rect();

        paint.getTextBounds(text, 0, text.length(), bounds);
    
        float bitmapMiddle = bitmap.getWidth() / 2.0f;
    
        Canvas canvas = new Canvas(bitmap);
        paint.setColor(Color.RED);
        canvas.drawText(text, bitmapMiddle - (bounds.right  / 2.0f), bitmap.getHeight(), paint);
        return bitmap;
    } 
    

    【讨论】:

    • 我试过你的代码,如果文本是长字符串,文本仍然不能完全显示。例如,尝试将此字符串作为文本:“Test text, test text : Test text, test text”。
    • 您可以使用字体大小来适应所有文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2013-01-25
    相关资源
    最近更新 更多