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); 
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM