思路:
建立一个bitmap副本
给imageview设置触摸监听
在两个触摸点之间画一条线canvas.drawLine(mStartx,mStarty,x,y,mPaint)
然后mImageView.setImageBitmap(mAltBitmap);
可以设置不同画笔颜色,粗细等
也可以改变画布颜色。
布局:
<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"
tools:context="cn.zsp.huahuaban.MainActivity">
<ImageView android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="320dp"
/>
</LinearLayout>
</pre>
代码:
cn.zsp.huahuaban;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "zsp";
private ImageView mImageView;
private Paint mPaint;
private Bitmap mAltBitmap;
private int mStarty;
private int mStartx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.iv);
//得到原图
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.sc);
mImageView.setImageBitmap(bitmap);
//获取副本
mAltBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.FILL);
// mPaint.setStrokeWidth(20);
final Canvas canvas=new Canvas(mAltBitmap);
canvas.drawBitmap(bitmap,new Matrix(),mPaint);
canvas.drawText("niafdsaf",0,0,mPaint);
mImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e(TAG, "onTouch: 按下了" );
mStartx = (int) event.getX();
mStarty = (int) event.getY();
break; case MotionEvent.ACTION_MOVE:
Log.e(TAG, "onTouch: 移动了" );
int x= (int) event.getX();
int y= (int) event.getY();
canvas.drawLine(mStartx,mStarty,x,y,mPaint);//两点间划线
mImageView.setImageBitmap(mAltBitmap);
mStartx=x;
mStarty=y;//重置
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, "onTouch: 离开了" );
break; }
return true;
}
});
}
}
</pre>