Android中如何将字符串转为Bitmap

作者: 核子飞弹 | 来源:发表于2018-06-06 10:07 被阅读72次

    过程

    1. 计算字符串绘制成图片时的图片大小
    2. 创建位图
    3. 绘制位图

    代码

        public static Bitmap fromText(float textSize, String text) {
            Paint paint = new Paint();
            paint.setTextSize(textSize);
            paint.setTextAlign(Paint.Align.LEFT);
            paint.setColor(Color.BLACK);
    
            Rect bound = new Rect();
            paint.getTextBounds(text, 0, text.length(), bound);
    
            Paint.FontMetrics fm = paint.getFontMetrics();
    
            int width = bound.width() + 6;
            int height = bound.height() + 4;
    
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawText(text, 0, height + fm.top - fm.ascent, paint);
            canvas.save();
    
            return bitmap;
        }
    

    示例

    将货币符号转成位图显示在控件左侧,将金额作为控件的文本值,可以使控件更好的表示金钱的概念

    Currency currency = Currency.getInstance("USD");
    Bitmap bitmap = fromText(36, currency.getSymbol());
    Drawable drawable = new BitmapDrawable(bitmap);
    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    view.setCompoundDrawables(drawable , null, null, null);
    

    相关文章

      网友评论

        本文标题:Android中如何将字符串转为Bitmap

        本文链接:https://www.haomeiwen.com/subject/frovsftx.html