packagexidian.dy.com.chujia;importandroid.content.Intent;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Matrix;importandroid.graphics.Paint;importandroid.net.Uri;importandroid.os.Bundle;importandroid.os.Environment;importandroid.support.v7.app.AppCompatActivity;importandroid.view.MotionEvent;importandroid.view.View;importandroid.widget.ImageView;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;public class MainActivity extendsAppCompatActivity {intpreX,preY;
Bitmap bmcpy;
@Overridepublic voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bm=BitmapFactory.decodeResource(getResources(), R.drawable.bg);
bmcpy=Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());final Paint paint = newPaint();final Canvas canvas = newCanvas(bmcpy);//设置画笔的颜色为红色
paint.setColor(Color.RED);
canvas.drawBitmap(bm,newMatrix(), paint);final ImageView iv =(ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bmcpy);if(iv != null)
iv.setOnTouchListener(newView.OnTouchListener() {
@Overridepublic booleanonTouch(View v, MotionEvent event) {int action =event.getAction();switch(action) {caseMotionEvent.ACTION_DOWN:
preX= (int) event.getX();
preY= (int) event.getY();break;caseMotionEvent.ACTION_UP:break;caseMotionEvent.ACTION_MOVE:int x = (int) event.getX();int y = (int) event.getY();
canvas.drawLine(preX, preY, x, y, paint);
iv.setImageBitmap(bmcpy);
preX=x;
preY=y;break;
}return true;
}
});
}//将画好的图片进行保存
public voidsave(){
File file= new File("/sdcard/tmp.png");try{
FileOutputStream fos= newFileOutputStream(file);
bmcpy.compress(Bitmap.CompressFormat.PNG,10,fos);
Intent intent= newIntent();//发出SDcard挂载广播来刷新MediaStore数据库
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
startActivity(intent);
}catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}