您的位置:首页 > 其它

自定义View

2016-07-18 10:55 323 查看
PathActivity

PathEffect来定义绘制效果,PathEffect有如下几个子类,没一个子类代表一种效果,然后通过Canvas里onDraw的方法沿着路径绘制图形。

ComposePathEffect

CornerPathEffect

DashPathEffect

DiscretePathEffect

PathDashPathEffect

SumPathEffect

package com.android.xiong.gridlayoutTest;

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.view.View;

public class PathActivity extends Activity {
/**

*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends View{
float phase;

               //七种不同的效果

PathEffect[] effects=new PathEffect[7];
int[] colors;
private Paint paint;
Path path;

public MyView(Context context) {
super(context);
// 创建path并初始化
paint=new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
path=new Path();
path.moveTo(0, 0);
for (int i = 1; i <=40; i++) {
//生成40个点,随机生成y轴坐标并练成一个path
path.lineTo(i*20, (float) (Math.random()*60));
//初始化7个颜色
colors=new int[]{
Color.BLACK,Color.BLUE,Color.DKGRAY,Color.GREEN,
Color.YELLOW,Color.RED,Color.MAGENTA}
;

}

}
@Override
protected void onDraw(Canvas canvas) {
//将背景颜色填充为白色
canvas.drawColor(Color.WHITE);
//不使用路径效果
effects[0]=null;
//使用CornerPathEffect
effects[1]=new CornerPathEffect(10);
//初始化DiscretePathEffect
effects[2]=new DiscretePathEffect(3.0f, 5.0f);
//
effects[3]=new DashPathEffect(new float[]{20, 10,5,10},phase);
//初始化PthDashPathEffect
Path p=new Path();
p.addRect(0, 0, 8, 8, Path.Direction.CCW);
effects[4]=new PathDashPathEffect(p, 12, phase, PathDashPathEffect.Style.ROTATE);
//初始化ComposePathEffect
effects[5]=new ComposePathEffect(effects[2], effects[4]);
effects[6]=new SumPathEffect(effects[4], effects[3]);
//将画布移动到(8,8)处开始绘制
//使用7种不同的路径效果,7种不同的颜色来绘制路径
for (int i = 0; i < effects.length; i++) {
paint.setPathEffect(effects[i]);
paint.setColor(colors[i]);
canvas.drawPath(path, paint);
canvas.translate(0, 60);
//转化60度

}
phase+=1;
//改变phase值,形成动画效果
invalidate();
//super.onDraw(canvas);
}
}

}

运行效果图如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: