画板
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
private ImageView imgView;
private Paint paint;
private float startX = 0;
private float startY = 0;
private Bitmap bitmap;
private Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
/**
* 初始化视图
*/
private void initViews(){
imgView = (ImageView)findViewById(R.id.iv_id);
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
imgView.setOnTouchListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.clear_id:
recycle();
createCanvasBitmap();
//设置空白bitmap到imgView
imgView.setImageBitmap(bitmap);
break;
case R.id.save_id:
saveBitmap();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN: //按下
if(bitmap == null){
createCanvasBitmap();
}
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_MOVE: //移动
float stopX = event.getX();
float stopY = event.getY();
canvas.drawLine(startX, startY, stopX, stopY, paint);
//更新起始点坐标
startX = event.getX();
startY = event.getY();
imgView.setImageBitmap(bitmap);
break;
}
return true;
}
/**
* 保存图片
*/
private void saveBitmap(){
String picFile = Environment.getExternalStorageDirectory().toString() + File.separator+System.currentTimeMillis()+".png";
OutputStream os = null;
try {
os = new FileOutputStream(picFile);
//bitmap保存到输出流
bitmap.compress(Bitmap.CompressFormat.PNG,100,os);
addImg(picFile);
Toast.makeText(this,"保存图片成功",Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this,"保存图片失败",Toast.LENGTH_SHORT).show();
} finally {
try {
if(os!=null){
os.flush();
os.close();
os = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 向相册中加入图片
* @param picFile
*/
private void addImg(String picFile){
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
//图片所在路径
values.put("_data",picFile);
//图片类型
values.put("mime_type","image/png");
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
resolver.insert(uri,values);
}
/**
* 回收bitmap
*/
private void recycle(){
if(bitmap!=null && !bitmap.isRecycled()){
bitmap.recycle();
}
}
/**
* 创建画布
*/
private void createCanvasBitmap() {
//创建一个和ImageView一样大小的bitmap
bitmap = Bitmap.createBitmap(imgView.getWidth(),imgView.getHeight(),Bitmap.Config.ARGB_8888);
//传递bitmap参数的含义:canvas所有的绘图操作都在bitmap上
canvas = new Canvas(bitmap);
canvas.drawColor(Color.GREEN);
}
}