本文主要是介绍【Android UI】Path 测量 PathMeasure ③ ( 使用 PathMeasure 绘制沿曲线运动的小球 ),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 一、使用 PathMeasure 绘制沿曲线运动的小球
- 二、代码示例
- 三、运行效果
一、使用 PathMeasure 绘制沿曲线运动的小球
绘制圆形曲线 : 创建 Path 对象 , 直接向其中添加 圆形曲线 即可 , 设置中心坐标以及半径 ;
// 绘制的 PathPath path = new Path();// 绘制圆形path.addCircle(0, 0, 300, Path.Direction.CW);canvas.drawPath(path, mPaint);
创建 Path 测量对象 :
// 圆形曲线测量PathMeasure pathMeasure = new PathMeasure(path, false);
获取指定长度位置的坐标点 :
// 获取特定点的 坐标 以及 切点pathMeasure.getPosTan(pathMeasure.getLength() * mProgress, pos, tan);// 在该特定点绘制圆形canvas.drawCircle(pos[0], pos[1], 20, mPaint);
定时绘制 : 在 onDraw 方法中 , 每次绘制进度都增加千分之五 , 本次绘制完毕后 , 立刻开始下一次绘制 ;
// 每次前进千分之五mProgress += 0.005;// 到达结束点后, 继续循环运动if (mProgress >= 1) mProgress = 0;// 触发下一次绘制invalidate();
二、代码示例
package kim.hsl.paintgradient.pathmeasure;import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;import androidx.annotation.Nullable;public class PathMeasureView extends View {/*** 画笔工具* 线性渐变渲染 需要设置给该 画笔工具*/private Paint mPaint;/*** 曲线上的点*/private float[] pos = {0F, 0F};/*** 曲线上点的切点*/private float[] tan = {0F, 0F};/*** 前进百分比, 0F ~ 1F*/private float mProgress;public PathMeasureView(Context context) {this(context, null);}public PathMeasureView(Context context, @Nullable AttributeSet attrs) {this(context, attrs, 0);}public PathMeasureView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);initPaint();}/*** 初始化 画笔工具, 主要是设置该画笔的渲染*/private void initPaint() {mPaint = new Paint();mPaint.setAntiAlias(true);mPaint.setColor(Color.BLUE);mPaint.setStyle(Paint.Style.STROKE);}@Overrideprotected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {super.onSizeChanged(width, height, oldWidth, oldHeight);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);// 每次前进千分之五mProgress += 0.005;// 到达结束点后, 继续循环运动if (mProgress >= 1) mProgress = 0;canvas.drawColor(Color.WHITE);canvas.translate(getWidth() / 2, getHeight() / 2);// 绘制的 PathPath path = new Path();// 绘制圆形path.addCircle(0, 0, 300, Path.Direction.CW);canvas.drawPath(path, mPaint);// 圆形曲线测量PathMeasure pathMeasure = new PathMeasure(path, false);// 获取特定点的 坐标 以及 切点pathMeasure.getPosTan(pathMeasure.getLength() * mProgress, pos, tan);// 在该特定点绘制圆形canvas.drawCircle(pos[0], pos[1], 20, mPaint);// 触发下一次绘制invalidate();}}
三、运行效果
运行时 , 圆是沿着曲线运动的 ;
这篇关于【Android UI】Path 测量 PathMeasure ③ ( 使用 PathMeasure 绘制沿曲线运动的小球 )的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!