Android日常开发 - 详解Paint搭配SweepGradient实现扫描渐变

Android日常开发 - 详解Paint搭配SweepGradient实现扫描渐变

👉关于作者

已经工作三年的95后程序员,坐标上海。平时在公司写Android原生App,业余时间会抽空学习Java后端,目标是成为全栈工程师,志同道合的可以私我聊聊haha。加入CSDN快4年了,看了很多优秀作者的博客收获很多。后面的时间里,我也会整理一些工作中使用到的知识分享出来。我的座右铭:人生在勤,不索何获。大家一起努力加油吧

👉正文部分

1、SweepGradient定义

扫描渐变,一般作用对象是圆或者弧线,从3点钟方向开始绘制

2、SweepGradient两个构造参数

//cx,cy:圆心坐标;color0:渐变起点颜色;color1:渐变终点颜色
SweepGradient(float cx, float cy, int color0, int color1)

//cx,cy:圆心坐标;colors:颜色数组;positions:设置颜色数组每个颜色起始位置,值范围0-1,0:三点钟方向,0.25:9点钟方向;以此类推
SweepGradient(float cx, float cy, int[] colors, float[] positions)

3、基本使用

1、核心代码

//设置扫描渐变
float cx = mWidth/2f;
float cy = mHeight/2f;
int radius = mWidth /2;
int startColor = mContext.getResources().getColor(R.color.blue);
int endColor = mContext.getResources().getColor(R.color.red);
//绿色,红色
int[] colors = new int[]{startColor,endColor};
//绿色对应0f,也就是起点颜色;红色对应1f,也就是终点颜色
float[] positions = new float[]{0f,1f};
SweepGradient sweepGradient = new SweepGradient(cx, cy, colors, positions);
mPaint.setShader(sweepGradient);
canvas.drawCircle(cx,cy,radius,mPaint);

2、效果图,起点是3点钟

在这里插入图片描述

4、配合Matrix使用进行起始点旋转,setLocalMatrix()

1、核心代码

//设置扫描渐变
float cx = mWidth/2f;
float cy = mHeight/2f;
int radius = mWidth /2;
int startColor = mContext.getResources().getColor(R.color.blue);
int endColor = mContext.getResources().getColor(R.color.red);
//绿色,红色
int[] colors = new int[]{startColor,endColor};
//绿色对应0f,也就是起点颜色;红色对应1f,也就是终点颜色
float[] positions = new float[]{0f,1f};
SweepGradient sweepGradient = new SweepGradient(cx, cy, colors, positions);
Matrix matrix = new Matrix();
//设置矩阵顺时针旋转180度
matrix.setRotate(180,cx,cy);
//设置矩阵,相当于sweepGradient起点顺时针旋转了180度,从三点钟开始顺时针旋转180度,也就是9点钟,也就是起点变成了9点钟方向
sweepGradient.setLocalMatrix(matrix);
mPaint.setShader(sweepGradient);
canvas.drawCircle(cx,cy,radius,mPaint);

2、效果图,发现旋转180度后起点是9点钟方向

在这里插入图片描述

5、冷知识

  1. 第二个构造参数,positions的起始位置是大于0的数值,比如0.1,那么0-0.1这段区间显示的是colors第一个颜色;
  2. 第二个构造参数,positions的终点位置是小于1的数值,比如0.9,那么0.9-1这段区间是无颜色的;

参考:自定义控件-Paint(3)_详解Paint的setShader(Shader shader)

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值