安卓手机触摸画线

1.  定义 MyPaintView 组件

public class MyPaintView extends View {
    private List<Point> allPoint = new ArrayList<Point>();
    public MyPaintView(Context context, AttributeSet attrs) {
        super(context, attrs);
        super.setBackgroundColor(Color.WHITE);
        super.setOnTouchListener(new OnTouchListenerImp());
    }

    private class OnTouchListenerImp implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //Point类记录当前的X和Y坐标
            Point p = new Point((int)event.getX(),(int)event.getY());
            if(event.getAction() == MotionEvent.ACTION_DOWN) {  //判断抬起
                allPoint = new ArrayList<Point>();  //开始新的记录
                allPoint.add(p);   //记录坐标点
            } else if(event.getAction() == MotionEvent.ACTION_UP) {
                allPoint.add(p);   //记录坐标点
                MyPaintView.this.postInvalidate();  //重绘
            }
                return true;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {  //进行绘图
        Paint p = new Paint();
        p.setColor(Color.RED);   //设置颜色
        if(allPoint.size()>1) {
            Iterator<Point> iter = allPoint.iterator();
            Point first = null;
            Point last = null;
            while(iter.hasNext()) {    //迭代输出
                if(first == null) {
                    first = (Point) iter.next();
                } else {
                    if(last != null) {
                        first = last;       //修改起始点
                    }
                    last = (Point) iter.next();   //结束点
                    canvas.drawLine(first.x,first.y,last.x,last.y,p);
                }
            }
        }

        super.onDraw(canvas);
    }
}

2.  在activity_main.xml 中要注意,MyPaintView是自定义的,要加入完整的包名

<com.example.administrator.ontouchtest.MyPaintView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/paintView"/>

3.  编写MainActivity

public class MainActivity extends AppCompatActivity {
        private TextView info = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
}

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值