效果:
其实画画板的原理很简单,就是首先记录下按下屏幕的点,然后每移动一下就让这两次移动的点连线,周而复始,图像就由很多条直线构成了。
核心代码 :
public class MainActivity extends Activity implements OnClickListener,OnSeekBarChangeListener {
private View red_view,green_view,blue_view; //控制画笔颜色的三块区域
private SeekBar seekBar; //控制画笔粗细的拖动条
private ImageView iv;
private Bitmap bitmap,backgroud; //画纸和背景图
private Canvas canvas; //画布
private Paint paint; //画笔
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
red_view = findViewById(R.id.red_view);
green_view = findViewById(R.id.green_view);
blue_view = findViewById(R.id.blue_view);
seekBar = (SeekBar) findViewById(R.id.seekbar);
iv = (ImageView) findViewById(R.id.iv);
iv.setImageResource(R.drawable.bg);
//拿到背景图
backgroud = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
//拿到和背景图一样大小的画纸
bitmap = Bitmap.createBitmap(backgroud.getWidth(), backgroud.getHeight(), backgroud.getConfig());
//把画纸固定在画布上
canvas = new Canvas(bitmap);
//拿到画笔
paint = new Paint();
paint.setColor(Color.BLACK);//设置画笔颜色为黑色
paint.setStyle(Style.STROKE);//设置画笔为空心
//添加处理规则
Matrix matrix = new Matrix();
//照着背景图画
canvas.drawBitmap(backgroud, matrix, paint);
red_view.setOnClickListener(this);
green_view.setOnClickListener(this);
blue_view.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
iv.setOnTouchListener(new OnTouchListener() {
float startX;
float startY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
//获取按下时的坐标
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
//获取移动时的坐标
case MotionEvent.ACTION_MOVE:
float stopX = event.getX();
float stopY = event.getY();
// // 在开始和结束坐标间画一条线
canvas.drawLine(startX, startY, stopX, stopY, paint);
//实时更新坐标(通过不断画线)
startX = event.getX();
startY = event.getY();
iv.setImageBitmap(bitmap);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.red_view:
//当点击红色区域的时候设置画笔颜色为红色
paint.setColor(Color.RED);
break;
case R.id.green_view:
//当点击绿色区域的时候设置画笔颜色为绿色
paint.setColor(Color.GREEN);
break;
case R.id.blue_view:
//当点击蓝色区域的时候设置画笔颜色为蓝色
paint.setColor(Color.BLUE);
break;
default:
break;
}
}
//拖动条的值改变的时候调用
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
//开始拖动时调用
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
//停止拖动时调用
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();//拖动条默认的最大值为100
paint.setStrokeWidth(progress/10f);//控制画笔的粗细范围(0-10)
}
}
试试觉得很简单呢,赶紧试试吧