2015-01-16 124 views
1

我有一個問題。如何將圖像保存到android自定義視圖文件?

我嘗試保存畫布圖像文件

這裏是我的工作。 1.創建畫布位圖對象(表格圖像)在畫布上 2.打印文本(使用的drawText) 3.save與bitmap.compress()方法

,但它僅保存原始的位圖(帶出來的文字)

我不知道如何保存文本打印的位圖文件? 這裏是我的代碼

protected class MyView extends View{ 

    public MyView(Context context){ 
     super(context); 
    } 

    public void onDraw(Canvas canvas){ 
     Paint pnt = new Paint(); 
     pnt.setColor(Color.BLACK); 
     canvas.scale(0.5f,0.5f); 
     Resources res = getResources(); 
     BitmapDrawable bd =(BitmapDrawable)res.getDrawable(R.drawable.hanhwa); 
     Bitmap bit = bd.getBitmap(); 
     canvas.drawBitmap(bit,0,0,null); 

     pnt.setTextSize(30); 
     canvas.drawText("hello",290,340,pnt); 
     canvas.restore(); 


     //file save// 
     File folder = new File(Environment.getExternalStorageDirectory()+"/DCIM/tmp"); 

     boolean isExist = true; 
     if(!folder.exists()){ 
      isExist = folder.mkdir(); 
     } 
     if(isExist){ 
      File file = null; 
      boolean isFileExist = false ; 
      file = new File(folder.getPath() + "/tmp.jpg"); 

      if(file != null && !file.exists()){ 
       try{ 
        isFileExist = file.createNewFile(); 
       } catch(IOException e){ 
        e.printStackTrace(); 
       } 
      } 
      else{ 
      } 

      if(file.exists()){ 
       FileOutputStream fos = null; 
       try{ 
        fos = new FileOutputStream(file); 

        bit.compress(Bitmap.CompressFormat.JPEG,100,fos); 
       } 
       catch(Exception e){ 
        e.printStackTrace(); 
       } 
       finally{ 
        try{ 
         fos.close(); 
        } 
        catch(IOException e){ 
         e.printStackTrace(); 
        } 
       } 

      } 
     } 
     else{ 
      //Toast.makeText(MyView.this,"foler not exist.",Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

回答

0
Bitmap.compresss() 

這種方法寫的位圖的壓縮版本指定的OutputStream。

將位圖實例傳遞給畫布

這裏是僞代碼。 (除了其他聲明,例如try-catch,聲明)

  1. Canvas c = new Canvas(bit);
  2. c.drawText(「hello」,290,340,pnt);
  3. b.compress(Bitmap.CompressFormat.JPEG,100,fos);

this post也會有幫助。

相關問題