首页 > 代码库 > android中Path的使用
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的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。