Android -- 图片画画板(canvas、paint、bitmap)
程序员文章站
2024-03-07 19:44:27
...
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/iv" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btn" android:layout_weight="6" android:onClick="save" android:layout_width="match_parent" android:layout_height="match_parent" android:text="保存图片" /> </LinearLayout>
MainActivity:
public class MainActivity extends Activity {
private Button button;
private ImageView p_w_picpathView;
private Bitmap baseBitmap;
private Canvas canvas;
private Paint paint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
p_w_picpathView=(ImageView) findViewById(R.id.iv);
paint=new Paint();
paint.setColor(Color.BLUE);
//创建一个可修改的Bitmap
baseBitmap=Bitmap.createBitmap(480, 320, Bitmap.Config.ARGB_8888);
canvas=new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
p_w_picpathView.setOnTouchListener(new OnTouchListener() {
//定义手指坐标
int startx;
int starty;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startx=(int) event.getX();
starty=(int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int newx=(int) event.getX();
int newy=(int) event.getY();
canvas.drawLine(startx, starty, newx, newy, paint);
//跟新画笔的开始位置
startx=(int) event.getX();
starty=(int) event.getY();
p_w_picpathView.setImageBitmap(baseBitmap);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
}
public void save(View v) {
try {
File file=new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".jpg");
FileOutputStream fos=new FileOutputStream(file);
baseBitmap.compress(CompressFormat.JPEG, 100, fos);//第一个参数为图片格式
fos.close();
Toast.makeText(this, "保存图片成功", 2000).show();
//模拟消息:SD卡被重新挂载了
Intent intent=new Intent();
intent.setAction(intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
Toast.makeText(this, "保存图片失败", 2000).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
因为要存入SD中,所以还要加一个权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
运行结果:
转载于:https://blog.51cto.com/shaotao/1299628