实现画图板
Posted zqxLonely
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现画图板相关的知识,希望对你有一定的参考价值。
package com.pingyijinren.helloworld; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import java.util.Iterator; /** * Created by Administrator on 2016/6/2 0002. */ public class MyPaintView extends View { private ArrayList<Point> allPoints=new ArrayList<Point>(); public MyPaintView(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundColor(Color.WHITE); setOnTouchListener(new OnTouchListener() { @Override public 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); MyPaintView.this.postInvalidate(); } return true; } }); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint=new Paint(); paint.setColor(Color.RED); if(allPoints.size()>1){ Iterator<Point> iterator=allPoints.iterator(); Point firstPoint=null; Point lastPoint=null; while(iterator.hasNext()){ if(firstPoint==null){ firstPoint=iterator.next(); } else{ if(lastPoint!=null){ firstPoint=lastPoint; } lastPoint=iterator.next(); canvas.drawLine(firstPoint.x,firstPoint.y,lastPoint.x,lastPoint.y,paint); } } } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.pingyijinren.helloworld.MainActivity"> <com.pingyijinren.helloworld.MyPaintView android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
package com.pingyijinren.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
以上是关于实现画图板的主要内容,如果未能解决你的问题,请参考以下文章