public class MainActivity extends AppCompatActivity implements View.OnTouchListener {canvas
private ImageView imgView;
private Paint paint;
private float startX = 0;
private float startY = 0;
private Bitmap bitmap;
private Canvas canvas;ide
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);this
initViews();
}orm
/**
* 初始化視圖
*/
private void initViews(){
imgView = (ImageView)findViewById(R.id.iv_id);圖片
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
imgView.setOnTouchListener(this);
}get
@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);
}it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return super.onCreateOptionsMenu(menu);
}io
@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;
}event
/**
* 保存圖片
*/
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();
}
}
}ast
/**
* 向相冊中加入圖片
* @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); }}