andorid 文字生成bitmap,带背景色(不能再简单了)

网上找了很多,没有合适,自己用画布完成

public class TextBitmap {
    /**
     * @Author Peng
     * @Date 2019/8/13 16:29
     * @Describe 画文字,自定义背景色,文字颜色,宽高
     * @return Bitmap
     */
    public static Bitmap getRectTextBitmap(String content, int bgColor, int w, int h, int textColor) {
        Bitmap whiteBgBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(whiteBgBitmap);
        // 矩形背景画笔
        Paint bgRect=new Paint();
        bgRect.setStyle(Paint.Style.FILL);
        bgRect.setColor(bgColor);
        RectF rectF=new RectF(0, 0, w, h);
        // 画矩形
        canvas.drawRect(rectF, bgRect);
        // 文字画笔
        Paint textPaint=new Paint();
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setStrokeWidth(8);
        textPaint.setTextSize(50);
        textPaint.setColor(textColor);
        textPaint.setTextAlign(Paint.Align.CENTER);
        //计算baseline
        Paint.FontMetrics fontMetrics=textPaint.getFontMetrics();
        float distance=(fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        float baseline=rectF.centerY()+distance;
        // 画文字
        canvas.drawText(content, rectF.centerX(), baseline, textPaint);
        return whiteBgBitmap;
    }


    /**
     * @Author Peng
     * @Date 2019/8/13 16:11
     * @Describe 画文字,圆形背景色
     */
    public static Bitmap getCircleTextBitmap(String content, int bgColor, int w, int h, int textColor) {
        Bitmap whiteBgBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(whiteBgBitmap);
        // 圆形背景画笔
        Paint bgRect=new Paint();
        bgRect.setStyle(Paint.Style.FILL);
        bgRect.setColor(bgColor);
        // 画圆
        canvas.drawCircle(w/2,h/2,w/2,bgRect);
        // 文字画笔
        Paint textPaint=new Paint();
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setStrokeWidth(8);
        textPaint.setTextSize(50);
        textPaint.setColor(textColor);
        textPaint.setTextAlign(Paint.Align.CENTER);
        //计算baseline
        Paint.FontMetrics fontMetrics=textPaint.getFontMetrics();
        float distance=(fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom;
        float baseline=h/2+distance;
        // 画文字
        canvas.drawText(content, canvas.getClipBounds().centerX(), baseline, textPaint);
        return whiteBgBitmap;
    }
}
// 使用方式
        int width=dip2px(50);
        int bgColor=Color.parseColor("#019FE8");
        iv_text.setImageBitmap(TextBitmap.getCircleTextBitmap("A",bgColor,width,width,Color.WHITE));

public  int dip2px(float dipValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

你可能感兴趣的:(andorid 文字生成bitmap,带背景色(不能再简单了))