android 隨手指移動劃線
阿新 • • 發佈:2019-02-07
自定義view
package com.example.myview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; public class DrawView extends View { private int x_begin; private int y_begin; private int x_end; private int y_end; private Canvas can = null; private Bitmap bit; public DrawView(Context context) { super(context); //this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT)); // invalidate(); bit = Bitmap.createBitmap(880,480,Config.ARGB_8888); can = new Canvas(); can.setBitmap(bit); } public DrawView(Context context,AttributeSet attribute) { super(context,attribute); bit = Bitmap.createBitmap(481,880,Config.ARGB_8888); can = new Canvas(); can.setBitmap(bit); } public void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bit, 0, 0,null); // canvas.drawCircle(x, y, 15, p); // canvas.drawLine(x_begin, y_begin, x_end, y_end, p); } public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN) { x_begin = (int) event.getX(); y_begin = (int) event.getY(); } if(event.getAction() == MotionEvent.ACTION_MOVE) { x_end = (int)event.getX(); y_end = (int)event.getY(); Paint p = new Paint(); p.setColor(Color.RED); can.drawLine(x_begin, y_begin, x_end, y_end, p); invalidate(); x_begin = x_end; y_begin = y_end; } return true; } }
2 xml佈局
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <com.example.myview.DrawView android:id = "@+id/myview" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>