安卓手機觸摸畫線

來源:互聯網
上載者:User

標籤:

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);        }}


安卓手機觸摸畫線

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.