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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainView = new PathView(this);
setContentView(mainView);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.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 stub
mPaint = 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")
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mPaint.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 block
e.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;
}
}
}
android绘制路径
最新推荐文章于 2024-05-15 17:34:21 发布