Android 提供的Path 类时一个非常有用的类.它可以预先在View 上将N个点连成一个”路径”,然后调用Canvas 的DrawPath(path , paint)即可沿着路径绘制图形.
package com.test.pathactivity;
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.DiscretePathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathDashPathEffect;
import android.graphics.PathEffect;
import android.graphics.SumPathEffect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
public class PathActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_path);
setContentView(new MyView(this));
}
class MyView extends View{
float phase;
PathEffect[] mEffects = new PathEffect[7];
int[] colors;
private Paint mPaint;
Path path;
public MyView(Context context) {
super(context);
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
//创建并初始化 Path
path = new Path();
path.moveTo(0,0);
for (int i = 0; i <= 15 ; i++) {
//生成 15个点,随机生成他们的 y坐标 并将他们连成一个 path
path.lineTo(i*30, (float) (Math.random()*60));
}
//初始化7个颜色
colors = new int[]{Color.YELLOW,Color.RED,Color.BLUE,Color.GREEN,Color.BLACK,Color.CYAN,Color.MAGENTA};
}
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
//将背景色 填充为白色
canvas.drawColor(Color.WHITE);
//下面初始化7种路径效果
//不使用路径效果
mEffects[0] = null;
//使用 CornerPathEffect 路径效果
mEffects[1] = new CornerPathEffect(10);
//使用 DiscretePathEffect
mEffects[2] = new DiscretePathEffect(3.3f,5.0f);
//初始化 DashPathEffect
mEffects[3] = new DashPathEffect(new float[]{20,10,5,10},phase);
//初始化 PathDashPathEffect
Path p = new Path();
p.addRect(0,0,8,8,Path.Direction.CCW);
mEffects[4] = new PathDashPathEffect(p,12,phase,PathDashPathEffect.Style.ROTATE);
mEffects[5] = new ComposePathEffect(mEffects[2],mEffects[4]);
mEffects[6] = new SumPathEffect(mEffects[4],mEffects[3]);
//将画布移动到(8,8)出 开始绘制
canvas.translate(8,8);
//依次使用7中不同路径效果,7中不同的颜色来绘制路径
for (int i = 0; i < mEffects.length; i++) {
mPaint.setPathEffect(mEffects[i]);
mPaint.setColor(colors[i]);
canvas.drawPath(path, mPaint);
canvas.translate(10,60);
}
//改变 phase 值 形成动画效果
phase+=1;
invalidate();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
}
下面 4条 是具有 动画效果的
本文介绍如何在Android中利用Path类实现复杂图形绘制,并通过PathEffect应用多种视觉效果,如CornerPathEffect、DiscretePathEffect等,同时展示了如何通过动画效果增强用户体验。
1万+

被折叠的 条评论
为什么被折叠?



