* 原理:两点之间用线连接起来
* 编写步骤:
1. 创建背景图的副本
2. 设置imageview的触摸监听
3. 把手指按下的坐标点和手指移动的坐标点连接起来
4. 把修改后的副本显示在imageview
package com.example.draw_picture; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { private Paint paint; private Bitmap copyBmp; private Canvas canvas; private ImageView iv; /** * 1. 创建背景图的副本 2. 设置imageview的触摸监听 3. 把手指按下的坐标点和手指移动的坐标点连接起来 4. 把修改后的副本显示在imageview */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.iv); //创建背景图的副本 Bitmap srcBmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg); paint = new Paint(); copyBmp = Bitmap.createBitmap(srcBmp.getWidth(), srcBmp.getHeight(), srcBmp.getConfig()); canvas = new Canvas(copyBmp); canvas.drawBitmap(srcBmp, new Matrix(), paint); //设置imageview的触摸监听 iv.setOnTouchListener(new OnTouchListener() { private float startX; private float startY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN://按下 //获取手指按下的xy坐标点 startX = event.getX(); startY = event.getY(); break; case MotionEvent.ACTION_MOVE://移动 //获取手指移动的xy坐标点 float stopX = event.getX(); float stopY = event.getY(); //把手指按下的坐标点和手指移动的坐标点连接起来 canvas.drawLine(startX, startY, stopX, stopY, paint); //5. 更新起始点的坐标 startX = stopX; startY =stopY; break; default: break; } //把修改后的副本显示在imageview iv.setImageBitmap(copyBmp); return true; } }); } public void red(View v){ paint.setColor(Color.RED); } public void green(View v){ paint.setColor(Color.GREEN); } public void blue(View v){ paint.setColor(Color.BLUE); } /** * 调整画笔的粗细 */ public void cx(View view){ paint.setStrokeWidth(5); } public void save(View v){ FileOutputStream os; try { os = new FileOutputStream(new File("/mnt/sdcard/jiezuo.jpg")); copyBmp.compress(CompressFormat.JPEG,100, os); Toast.makeText(this, "大师,您的杰作保存在:/mnt/sdcard/jiezuo.jpg", 0).show(); } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(this, "sorry,大师,您的杰作保存失败", 0).show(); } } }
添加SD卡的权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />