原文:http://blog.csdn.net/lessu/archive/2010/04/28/5539748.aspx
很多人在做画图软件的时候找不到保存画好图片的方法。。
其实可以在bitmap上面画,然后保存bitmap就可以了,而不需要找屏幕截图的函数了。。。
package com.android.DrawTest; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.Window; import android.view.WindowManager; public class DrawTest extends Activity { private DrawView dv; private Bitmap myBitmap; Canvas canvas; //用于在Bitmap上面画图 private File file; private FileOutputStream out; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); dv=(DrawView)findViewById(R.id.DrawView); myBitmap=Bitmap.createBitmap(400, 400, Config.ARGB_8888); canvas=new Canvas(myBitmap); canvas.drawColor(Color.WHITE); file =new File("//sdcard//","Test.jpg");//输出路径 try { out=new FileOutputStream(file);//设置输出流 } catch (FileNotFoundException e) { e.printStackTrace(); } } @Override public boolean onTouchEvent(MotionEvent me){ Paint paint; paint=new Paint(); paint.setColor(Color.RED); switch(me.getAction()) { case MotionEvent.ACTION_DOWN: //画点 canvas.drawCircle(me.getX(), me.getY(), 10, paint); dv.Draw(myBitmap); break; } return false; } @Override public void onDestroy(){ try { //退出时保存 myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } super.onDestroy(); } }
surfaceview
package com.android.DrawTest; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class DrawView extends SurfaceView implements SurfaceHolder.Callback{ private SurfaceHolder mSurfaceHolder; private Context mContext; public DrawView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub mSurfaceHolder=getHolder(); mContext=context; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } public void Draw(Bitmap bitmap){ Canvas c=mSurfaceHolder.lockCanvas(); c.drawBitmap(bitmap, 0,0, null); mSurfaceHolder.unlockCanvasAndPost(c); } }