随手涂鸦小示例:
xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/imageView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:onClick="save"/>
<Button
android:id="@+id/sb_red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="清除"
android:onClick="clear"/>
</LinearLayout>
</LinearLayout>
Java功能代码:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
private ImageView imageView;
private Bitmap bitmap;
private Canvas canvas;
//起始坐标
private int startX;
private int startY;
private Paint paint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
imageView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if (bitmap == null){
bitmap = Bitmap.createBitmap(imageView.getWidth(),imageView.getHeight(),Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
paint = new Paint();
paint.setColor(Color.RED); //画笔颜色为红色
paint.setStrokeWidth(5); //线条宽度5磅
}
startX = (int)event.getX();
startY = (int)event.getY();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int)event.getX();
int moveY = (int)event.getY();
canvas.drawLine(startX,startY,moveX,moveY,paint);
imageView.setImageBitmap(bitmap);
startX = moveX;
startY = moveY;
break;
default:
break;
}
return true;
}
public void clear(View view){
bitmap = null;
imageView.setImageBitmap(null);
}
public void save(View view){
if (bitmap == null){
Toast.makeText(this,"没有图片可以保存",Toast.LENGTH_LONG).show();
return;
}
Log.i("path","path =" + getFilesDir());
File file = new File(getFilesDir(),"pic"+System.currentTimeMillis()+".jpg");
FileOutputStream stream = null;
try{
stream = new FileOutputStream(file);
//以jpeg的图形格式将当前图片以流的形式输出
boolean compress = bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
if (compress){
Toast.makeText(this,"保存成功" + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"保存失败",Toast.LENGTH_SHORT).show();
}
}catch (FileNotFoundException e){
Toast.makeText(this,"保存失败" + e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}finally {
if (stream != null){
try{
stream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
文件流的输入输出这块挺懵的,还需要再看看,此处表示从屏幕输出到内存,用的 FileOutputStream,其中存储路径getFilesDir()表示路径在 /data/data/包名/file/ 下。 希望用到的时候有的看,可以加些调色板啥的优化下。