SKY外语计算机学习
标题:
Android画板
[打印本页]
作者:
SKY精英
时间:
2013-6-13 10:27
标题:
Android画板
本帖最后由 sky_yx 于 2015-12-30 14:07 编辑
思路:
自定义CustomView,重写onTouch(),和onDraw()。在onTouch中识别触屏事件,并记录触屏发生的位置。为了在ACTION_DOWN发生后能够接收到后续的触屏事件,我们需要让onTouch()返回true。
Java代码
package com.ipjmc.hello;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View {
private int mLastX, mLastY; //上次触屏的位置
private int mCurrX, mCurrY; //当前触屏的位置
private Bitmap mBitmap; //保存每次绘画的结果
private Paint mPaint;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
//先将结果画到Bitmap上
Canvas tmpCanvas = new Canvas(mBitmap);
tmpCanvas.drawLine(mLastX, mLastY, mCurrX, mCurrY, mPaint);
//再把Bitmap画到canvas上
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mLastX = mCurrX;
mLastY = mCurrY;
mCurrX = (int) event.getX();
mCurrY = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = mCurrX;
mLastY = mCurrY;
break;
default:
break;
}
invalidate();
return true; //必须返回true
}
}
作者:
Kill
时间:
2013-10-6 19:12
up and support
作者:
857401199
时间:
2015-3-16 11:45
本帖最后由 sky_yx 于 2015-12-30 14:07 编辑
新人顶帖!!!!
欢迎光临 SKY外语计算机学习 (http://join.skywj.com/)
Powered by Discuz! X2.5