Android 使用Canvas在图片上绘制文字

一个小应用,在图片上绘制文字,以下是绘制文字的方法,并且能够实现自动换行,字体自动适配屏幕大小 

private void drawNewBitmap(ImageView imageView, String str) {
          Bitmap photo = BitmapFactory.decodeResource(this.getResources(), R.drawable.background);
          int width = photo.getWidth();
          int hight = photo.getHeight();
          //建立一个空的Bitmap
          Bitmap icon = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_8888);
          // 初始化画布绘制的图像到icon上
          Canvas canvas = new Canvas(icon);
          // 建立画笔
          Paint photoPaint = new Paint(); 
          // 获取更清晰的图像采样,防抖动
          photoPaint.setDither(true); 
          // 过滤一下,抗剧齿
          photoPaint.setFilterBitmap(true);
          
          Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());// 创建一个指定的新矩形的坐标
          Rect dst = new Rect(0, 0, width, hight);// 创建一个指定的新矩形的坐标
          canvas.drawBitmap(photo, src, dst, photoPaint);// 将photo 缩放或则扩大到dst使用的填充区photoPaint
      //自定义的画笔
          TextPaint textPaint=myTextPaint();
       drawText(canvas,textPaint,str,45,hight/5,width);
          
          canvas.save(Canvas.ALL_SAVE_FLAG);
          canvas.restore();
          
          imageView.setImageBitmap(icon);
          saveMyBitmap(this,icon);
    }
//设置画笔的字体和颜色
    public TextPaint myTextPaint(){
         
         TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
         int TEXT_SIZE = Math.round(25 * getRATIO());
         textPaint.setTextSize(TEXT_SIZE);// 字体大小
              textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
              textPaint.setColor(Color.argb(255,94,38,18));// 采用的颜色
              return textPaint;
//写入文字,自动换行的方法
    public void drawText(Canvas canvas, TextPaint Paint,String textString,int x,int y,int width) {  
        //int Width=Math.round(width* getRATIO());
        int start_x=Math.round(x * getRATIO());
        int start_y=Math.round(y * getRATIO());
        StaticLayout staticLayout=new StaticLayout(textString, Paint, width-start_x*2,  
                             Alignment.ALIGN_NORMAL, 1.5f, 0.0f, false);  
          
        //绘制的位置  
        canvas.translate(start_x, start_y);  
        staticLayout.draw(canvas); 
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值