本文主要是介绍安卓手机触摸画线,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 {@Overridepublic 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;}}@Overrideprotected 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.MyPaintViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:id="@+id/paintView"/>
3. 编写MainActivity
public class MainActivity extends AppCompatActivity {private TextView info = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}
}
这篇关于安卓手机触摸画线的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!