android绘制路径

来源:互联网 发布:传智播客php培训 编辑:程序博客网 时间:2024/06/07 10:44
package com.my.apitest;import android.os.Bundle;import android.util.Log;import android.view.View;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.ComposePathEffect;import android.graphics.CornerPathEffect;import android.graphics.DashPathEffect;import android.graphics.Paint;import android.graphics.Path;import android.graphics.PathEffect;public class MainActivity extends Activity {private PathView mainView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mainView = new PathView(this);setContentView(mainView);}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();mainView.drawC();}class PathView extends View {private Paint mPaint;private PathEffect cornerEffect; // 圆角效果private PathEffect dashEffect; // 断点效果private PathEffect composeEffect; // 组合效果private Path path; // 路径private Canvas canvas; // 画布,从onDraw方法里面获取public PathView(Context context) {super(context);// TODO Auto-generated constructor stubmPaint = new Paint();cornerEffect = new CornerPathEffect(10);dashEffect = new DashPathEffect(new float[] { 10, 5, 5, 5 }, 1);composeEffect = new ComposePathEffect(cornerEffect, dashEffect);path = makePath();}@SuppressLint("DrawAllocation")@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubmPaint.setStyle(Paint.Style.STROKE);mPaint.setStrokeWidth(6);canvas.translate(50, 200);mPaint.setColor(Color.BLACK);// mPaint.setPathEffect(mEffect);// mPaint.setPathEffect(dashEffect);mPaint.setPathEffect(composeEffect);// canvas.drawPath(path, mPaint);this.canvas = canvas;}/** * 测试canvas不在onDraw()方法里面同样可以使用, 但是要刷新调用postInvalidate()进行异步刷新, * 如果使用invalidate()则报错 */public void drawC() {new Thread() {public void run() {while (!this.isInterrupted()) {if (canvas != null) {path = makePath();canvas.translate(50, 200);canvas.drawPath(path, mPaint);//绘制PathView.this.postInvalidate();//刷新,执行onDraw()方法Log.e("haiyong.liu", "run");}try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};}.start();}/** * 初始化路径点 *  * @return */private Path makePath() {Path p = new Path();p.moveTo(0, 0);for (int i = 1; i <= 15; i++) {p.lineTo(i * 20, (float) Math.random() * 35);}return p;}}}

0 0
原创粉丝点击