Android实现渐色变圆形

看到一个渐变色圆形圆环,效果不错,自己动手做一个。具体思路是继承View,重写onDraw()方法,绘制圆形边界,添加渐变。

渐变用到LinearGradient。看一下它的定义:

android.graphics. LinearGradient.LinearGradient( float x0, float y0, float x1, float y1, int[] colors, float[] positions, TileMode tile)

Create a shader that draws a linear gradient along a line.

Parameters:
x0 The x-coordinate for the start of the gradient line
y0 The y-coordinate for the start of the gradient line
x1 The x-coordinate for the end of the gradient line
y1 The y-coordinate for the end of the gradient line
colors The colors to be distributed along the gradient line
positions May be null. The relative positions [0..1] of each corresponding color in the colors array. If this is null, the the colors are distributed evenly along the gradient line.
tile The Shader tiling mode


前四个参数,是渐变区域的左上右下坐标。
第五个参数是颜色数组。
第六个参数是颜色对应位置,如果为空,则颜色梯度变化。
最后一个参数,是结尾模式,也就是渐变结尾留白的处理方式,有填充,镜面,重复等模式。

看代码:

package com.example.ring;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;

public class RotateRing extends View {
	// 颜色数组,定义渐变色;
	private int[] colors;

	public RotateRing(Context context) {
		this(context, null);
	}

	public RotateRing(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public RotateRing(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		colors = new int[] {// 渐变色数组 7色
		0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00,
				0xFFFF0000 };
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		float radius = 210;	//圆半径
		int cX = getWidth() / 2;	//圆心
		int cY = getHeight() / 2;

		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setStyle(Paint.Style.STROKE); // 设置空心
		paint.setStrokeWidth(2); // 设置圆环的宽度

		LinearGradient shader = new LinearGradient(cX - radius, cY - radius, // 渐变区域,左上右下
				cX + radius, cY + radius, colors, null, Shader.TileMode.REPEAT);

		paint.setShader(shader);
		canvas.drawCircle(cX, cY, radius, paint);// 画圆
		SystemClock.sleep(500);
		rotateArray(colors);
	}

	/**
	 * 改变颜色数组内颜色值位置,实现颜色转动
	 * @param arr 颜色数组
	 */
	public void rotateArray(int[] arr) {
		int tmp = arr[0];
		for (int i = 0; i < arr.length - 1; i++) {
			arr[i] = arr[i + 1];
		}
		arr[arr.length - 1] = tmp;
		invalidate();	//重绘
	}
}
运行效果:



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值