自定義View(簡單一個畫板)
阿新 • • 發佈:2018-12-15
畫板
- 程式碼
public class PaintView extends View {
private Paint mPaint;//畫筆工具 private Path mPath;//路徑 public PaintView(Context context) { super(context); init(); } public PaintView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PaintView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init(){ mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE);//設定畫筆為邊線樣式,另外還有FILL全填充 mPaint.setColor(Color.BLACK);//設定畫筆顏色 mPaint.setStrokeWidth(5);//設定邊線寬度 mPath = new Path();//新建路徑 } /** * @author dingtao * @date 2018/11/29 4:44 PM * * 觸控方法 */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_UP://手指擡起 break; case MotionEvent.ACTION_DOWN://手指按下,路徑移動到觸控點 mPath.moveTo(event.getX(),event.getY());//路徑移動到觸控點 break; case MotionEvent.ACTION_MOVE://手指移動 mPath.lineTo(event.getX(),event.getY());//路徑連線到移動的點 break; } invalidate();//重新整理控制元件,回撥onDraw方法 return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawPath(mPath,mPaint);//畫路徑 }
-
佈局
直接託自定義控制元件就可以
-
效果
可以拓展 + 一個圓形放在畫板中
實現觸控圓形,拖動圓形的效果
修改方法中的值就可以
public boolean onTouchEvent(MotionEvent event) { x = event.getX(); y = event.getY(); /* switch (event.getAction()){ case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE: mPath.moveTo(event.getX(),event.getY()); break; case MotionEvent.ACTION_DOWN: mPath.lineTo(event.getX(), event.getY()); x = event.getX(); y = event.getY(); break; }*/ //***************** invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //canvas畫布**** canvas.drawCircle(x,y,100,myPaint); //canvas.drawPath(mPath,myPaint); }