黄沙百战穿金甲,不破楼兰终不还。这篇文章主要讲述android中Path的使用相关的知识,希望能为你提供帮助。
实现一个简单的绘图工具:(在视图中可以任意绘制,点击清除按钮,可重新绘制,类似我画你猜)
自定义视图代码:
public class MySurfaceView2 extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener { private Path mPath = new Path(); private Paint mPaint = new Paint(); public MySurfaceView2(Context context) { super(context); init(); }public MySurfaceView2(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init(){setOnTouchListener(this); getHolder().addCallback(this); } public void draw(){ Canvas canvas = getHolder().lockCanvas(); canvas.drawColor(Color.WHITE); canvas.drawPath(mPath,mPaint); getHolder().unlockCanvasAndPost(canvas); } //清理画布 public void clear(){ mPath.reset(); draw(); }@Override public void surfaceCreated(SurfaceHolder surfaceHolder) { }@Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { draw(); }@Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) {}@Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN: mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.RED); mPath.moveTo(motionEvent.getX(),motionEvent.getY()); break; case MotionEvent.ACTION_MOVE: //生成线条 mPath.lineTo(motionEvent.getX(), motionEvent.getY()); draw(); break; } return true; } }
在xml中加载自定义视图:
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> < com.example.lance.test2.MySurfaceView2 android:id="@+id/my_surface" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"/> < Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清除"/> < /LinearLayout>
在主活动代码:
public class MainActivity extends AppCompatActivity { private MySurfaceView2 mMySurfaceView2; private Button mButton; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.four); mMySurfaceView2 = (MySurfaceView2) findViewById(R.id.my_surface); mButton = (Button) findViewById(R.id.btn); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mMySurfaceView2.clear(); } }); }}
【android中Path的使用】
推荐阅读
- Android自定义标签列表控件LabelsView解析
- Android四大组件——ContentProvider
- Android学习总结 ———— Handler 的使用
- Android键盘事件
- Android测试(从零开始2——local单元测试)
- 安卓开源项目周报0315
- Android Activity 和 ViewGroup中事件触发和传递机制
- android shape.xml 属性详解
- C#方法代理/委托(delegate)用法介绍和示例