Android 使用Paint和Canvas将文字保存为图片

这里是使用Paint和Canvas直接将文字绘制成图片的方案。
如果是界面上显示的文字的话其实也可以使用文字的容器View的Bitmap来生成图片。

直接上代码,说明写注释里了

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;

import java.io.FileOutputStream;

/**
 * 生成图片
 * Created by QZD on 2017/5/8.
 */

public class bitmapFactory {
    private static int imageH=15;//图片高
    private static int imageW=270;//图片宽
    private static float brushSize=20;//画笔粗细
    private static int brushColor=Color.WHITE;//画笔颜色
    private static int bgColor=Color.RED;//背景颜色
    private static int imageQuality=100;//图片压缩质量

    /**
     * 绘制图片
     * @param path 生成图片的地址
     * @param _msg 文字
     * @return
     */
    public static boolean writeImage(String path,String _msg){
        try {
            Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);//Paint.ANTI_ALIAS_FLAG参数开启抗锯齿
            p.setColor(brushColor);
            p.setTextSize(brushSize);

            //创建一个矩形来获取文字区域宽高,作为图片大小
            Rect rect = new Rect();
            p.getTextBounds(_msg,0,_msg.length(),rect);
            imageW = rect.width();
            imageH = rect.height();

            Bitmap bitmap = Bitmap.createBitmap(imageW, imageH, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(bgColor);
            canvas.drawText(_msg, 0, brushSize, p);//注意这里的y参数是baseline的位置而不是文字开始或中心的位置

            Log.d("LOGCAT", "path:"+path);
            //将Bitmap保存为png图片
            FileOutputStream out = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, imageQuality, out);
            Log.d("LOGCAT", "png done");
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容