本文主要是介绍android实战项目二实现画板效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现画图板的效果ontouchevent
需要有一个自定义的组件用android绘图的重点
下面是自定义的类
先重写这个view的ontouchListener方法的得到手指的坐标点
再重写view的ondraw方法 来画出手指移动的轨迹
public class MypiantView extends View {private List<Point> allpoints = new ArrayList<Point>();;// 用容器来保存所有坐标public MypiantView(Context context, AttributeSet attrs) {super(context, attrs);super.setBackgroundColor(Color.WHITE);super.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {Point point = new Point((int) event.getX(), (int) event.getY());if (event.getAction() == MotionEvent.ACTION_DOWN) {allpoints = new ArrayList<Point>();// 初始化allpoints.add(point);} else if (event.getAction() == MotionEvent.ACTION_UP) {allpoints.add(point);} else if (event.getAction() == MotionEvent.ACTION_MOVE) {allpoints.add(point);MypiantView.this.postInvalidate();// 重新绘制}return true;// 表示不再执行了}});}// 重写andraw方法@Overrideprotected void onDraw(Canvas canvas) {Paint paint = new Paint();paint.setColor(Color.RED);if (allpoints.size() > 1) {// 用集合来装点,遍历每个点Iterator<Point> iterator = allpoints.iterator();Point firstPoint = null;// 开始点Point lastpPoint = null;// 结束点while (iterator.hasNext()) {if (firstPoint == null) {// 找到开始点firstPoint = (Point) iterator.next();} else {if (lastpPoint != null) {firstPoint = lastpPoint;}lastpPoint = (Point) iterator.next();canvas.drawLine(firstPoint.x, firstPoint.y, lastpPoint.x, lastpPoint.y, paint);// 画线}}}super.onDraw(canvas);}
}
再配置xml文件将自定义view导入
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <org.yayun.demo.MyPaintView android:id="@+id/paintView" android:layout_width="fill_parent" android:layout_height="fill_parent" > </org.yayun.demo.MyPaintView>
</LinearLayout>
最后在activity中引用布局文件xml
public class MyviewDraw extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.setContentView(R.layout.ontouchdraw);}
}
最后就可以运行了成功用手指在手机屏幕上画出了一条红线!!!
这篇关于android实战项目二实现画板效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!