Android之Path类
16lz
2021-01-25
Path类可以预先在View上将N个点连成一条"路径",然后调用Canvas的drawPath(path,paint)即可沿着路径绘制图形
Android还为路径绘制提供了PathEffect来定义绘制效果,PathEffect包含如下子类
ComposePathEffect
CornerPathEffect
DashPathEffect
DiscretePathEffect
PathDashPathEffect
SumPathEffect
下面的示例将会逐一使用上面的绘制效果
package com.android.xiong.pathtest;import android.os.Bundle;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.view.Menu;import android.view.View;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {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);paint = new Paint();paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(4);// 创建并初始化Pathpath = new Path();path.moveTo(0, 0);for (int i = 1; i <= 15; i++) {// 生成15个点,随机生成它们的坐标,并将它们连成一条Pathpath.lineTo(i * 20, (float) Math.random() * 60);}// 初始化7个颜色colors = new int[] { Color.RED, Color.BLUE, Color.GREEN,Color.YELLOW, Color.BLACK, Color.MAGENTA, Color.CYAN };}@Overrideprotected void onDraw(Canvas canvas) {// 将背景填充白色canvas.drawColor(Color.WHITE);// -----下面开始初始化7中路径效果-------// 不实用路径effects[0] = null;// 使用CornerPathEffect路径效果effects[1] = new CornerPathEffect(10);// 初始化DiscretePathEffecteffects[2] = new DiscretePathEffect(3.0f, 5.0f);// 初始化DashPathEffecteffects[3] = new DashPathEffect(new float[] { 20, 10, 5, 10 },phase);Path p = new Path();p.addRect(0, 0, 8, 8, Path.Direction.CCW);effects[4] = new PathDashPathEffect(p, 12, phase,PathDashPathEffect.Style.ROTATE);// 初始化PathDashPasheEffecteffects[5] = new ComposePathEffect(effects[2], effects[4]);effects[6] = new ComposePathEffect(effects[4], effects[3]);// 将画布移动到(8,8)处开始绘制canvas.translate(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);}// 改变phase值,形成动画效果phase += 1;invalidate();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
更多相关文章
- Android(安卓)Toast 总结
- Android音频架构概览
- Android会根据内容自动变色的TextView
- Android(安卓)RadioButton+Viewpager+Fragment实现底部导航栏
- Android(安卓)textview 不使用ScrollView也可滚动的方法
- google map APIKEY
- android 问题汇总系列之四
- 窗口透明样式示例
- RecyclerView 滚动条 长宽设置