/**
* 在图片上作画
*
* @author admin
* @time 2015年2月8日 上午1:12:18
*/
public class MainActivity extends Activity implements OnTouchListener {
private ImageView mImageView;
private Bitmap bitmap;
private Canvas canvas;
private float downX;
private float downY;
private Paint paint;
private EditText etPaintWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到控件
mImageView = (ImageView) findViewById(R.id.iv);
etPaintWidth = (EditText) findViewById(R.id.et_paintWidth);
// 为图片控件设置触摸事件
mImageView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:// 按下
if (bitmap == null) {
// 创建一张空白图片,宽,高和ImageView一样
bitmap = Bitmap.createBitmap(mImageView.getWidth(),
mImageView.getHeight(), Config.ARGB_8888);
// 把空白图片设置给Canvas画画板, canvas所绘制的东西都绘制到当前图片Bitmap上
canvas = new Canvas(bitmap);
// 创建一个画笔
paint = new Paint();
// 设置画笔的颜色
paint.setColor(Color.RED);
// 设置画笔画线时的粗细
String spaintWidth = etPaintWidth.getText().toString().trim();
int paintWidth = Integer.valueOf(spaintWidth);
paint.setStrokeWidth((float) paintWidth);
// 给画布画一个背景色
canvas.drawColor(Color.YELLOW);
}
downX = event.getX();
downY = event.getY();
System.out.println("按下了...:X:" + downX + ",Y:" + downY);
break;
case MotionEvent.ACTION_MOVE:
float moveX = event.getX();
float moveY = event.getY();
// 开始画线, 这一行代码执行完毕, Bitmap中有一条线了.
canvas.drawLine(downX, downY, moveX, moveY, paint);
mImageView.setImageBitmap(bitmap);
downX = moveX;
downY = moveY;
break;
case MotionEvent.ACTION_UP:
System.out.println("抬起了.......");
break;
}
return true;
}
/**
* 将手绘的图片保存到SD卡中
*
* @param v
*/
public void save(View v) {
if (bitmap != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("/mnt/sdcard/hehe.jpg");
bitmap.compress(CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<RelativeLayout 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"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_paintWidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入画笔的粗细度" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/et_paintWidth" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="save"
android:text="保存" />
</RelativeLayout>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />