android 中渐变的实现和SweepGradient 圆形渐变重点注意

Android 的自定义View神通广大,可以实现各种复杂的样式,渐变圆弧就是其中的一种。

1 shape 实现渐变

这个比较简单就是定义一个渐变的shape。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="0"
        android:endColor="#FFC54E"
        android:startColor="#FF9326"
        android:type="linear" />
    <corners
        android:bottomLeftRadius="25dp"
        android:bottomRightRadius="25dp"
        android:topLeftRadius="25dp"
        android:topRightRadius="25dp" />
</shape>

在这里插入图片描述

图片右侧的黄色色块就是渐变,使用时直接设置背景。

2 LinearGradient

2.1 第一种

public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)
/**
* Create a shader that draws a linear gradient along a line.
*
* @param x0 The x-coordinate for the start of the gradient line
* @param y0 The y-coordinate for the start of the gradient line
* @param x1 The x-coordinate for the end of the gradient line
* @param y1 The y-coordinate for the end of the gradient line
* @param color0 The color at the start of the gradient line.
* @param color1 The color at the end of the gradient line.
* @param tile The Shader tiling mode
*/
x0,y0,x1,y1是起始位置和渐变的结束位置,color0,color1是渐变颜色,最后一个参数表示绘制模式:

Shader.TileMode有3种参数可供选择,分别为CLAMP、REPEAT和MIRROR:

[1] CLAMP的作用是如果渲染器超出原始边界范围,则会复制边缘颜色对超出范围的区域进行着色
[2] REPEAT的作用是在横向和纵向上以平铺的形式重复渲染位图
[3] MIRROR的作用是在横向和纵向上以镜像的方式重复渲染位图

2.2 第二种

public LinearGradient (float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile);
/**
* Create a shader that draws a linear gradient along a line.
*
* @param x0 The x-coordinate for the start of the gradient line
* @param y0 The y-coordinate for the start of the gradient line
* @param x1 The x-coordinate for the end of the gradient line
* @param y1 The y-coordinate for the end of the gradient line
* @param colors The colors to be distributed along the gradient line
* @param 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.
* @param tile The Shader tiling mode
*/

x0,y0,x1,y1 参数和上面一样,tile和上面一样。
colors表示渐变的颜色数组;
positions指定颜色数组的相对位置

package com.example.hpuzz.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

public class ViewDemo extends View {
    public ViewDemo(Context context) {
        super(context);
    }

    public ViewDemo(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewDemo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        LinearGradient linearGradient = new LinearGradient(0, 0, 0, getMeasuredHeight(),new int[]{Color.RED, Color.BLUE}, null, LinearGradient.TileMode.REPEAT);
        paint.setShader(linearGradient);
        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics()), (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics()));
    }
}

在这里插入图片描述

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        float[] position = new float[3];
        position[0] = 0.0f;
        position[1] = 0.8f;
        position[2] = 1.0f;

        LinearGradient linearGradient = new LinearGradient(0, 0, 0, getMeasuredHeight(),new int[]{Color.RED,Color.GREEN, Color.BLUE}, position, LinearGradient.TileMode.REPEAT);
        paint.setShader(linearGradient);
        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint);
    }

在这里插入图片描述

可以看到position的取值范围[0,1],作用是指定某个位置的颜色值,如果传null,渐变就线性变化。

3 SweepGradient

 /**
     * A Shader that draws a sweep gradient around a center point.
     *
     * @param cx       The x-coordinate of the center
     * @param cy       The y-coordinate of the center
     * @param colors   The colors to be distributed between around the center.
     *                 There must be at least 2 colors in the array.
     * @param positions May be NULL. The relative position of
     *                 each corresponding color in the colors array, beginning
     *                 with 0 and ending with 1.0. If the values are not
     *                 monotonic, the drawing may produce unexpected results.
     *                 If positions is NULL, then the colors are automatically
     *                 spaced evenly.
     */
    public SweepGradient(float cx, float cy,
            @NonNull @ColorInt int colors[], @Nullable float positions[]) {
        if (colors.length < 2) {
            throw new IllegalArgumentException("needs >= 2 number of colors");
        }
        if (positions != null && colors.length != positions.length) {
            throw new IllegalArgumentException(
                    "color and position arrays must be of equal length");
        }
        mType = TYPE_COLORS_AND_POSITIONS;
        mCx = cx;
        mCy = cy;
        mColors = colors.clone();
        mPositions = positions != null ? positions.clone() : null;
    }

    /**
     * A Shader that draws a sweep gradient around a center point.
     *
     * @param cx       The x-coordinate of the center
     * @param cy       The y-coordinate of the center
     * @param color0   The color to use at the start of the sweep
     * @param color1   The color to use at the end of the sweep
     */
    public SweepGradient(float cx, float cy, @ColorInt int color0, @ColorInt int color1) {
        mType = TYPE_COLOR_START_AND_COLOR_END;
        mCx = cx;
        mCy = cy;
        mColor0 = color0;
        mColor1 = color1;
        mColors = null;
        mPositions = null;
    }

cx,cy,圆的中心坐标。
color0,color1渐变颜色
colors渐变颜色数组
positions 颜色位置,范围[0,1]

package com.example.hpuzz.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

public class ViewDemo2 extends View {
    public ViewDemo2(Context context) {
        super(context);
    }

    public ViewDemo2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewDemo2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(15);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeCap(Paint.Cap.ROUND);
       /* float[] position = new float[3];
        position[0] = 0.0f;
        position[1] = 0.8f;
        position[2] = 1.0f;*/

       // SweepGradient linearGradient = new SweepGradient(getMeasuredWidth()/2,getMeasuredHeight()/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, position);
        SweepGradient linearGradient = new SweepGradient((getMeasuredWidth() - 40)/2,(getMeasuredHeight() - 40)/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, null);
        Matrix matrix = new Matrix();
        matrix.setRotate(180, getMeasuredWidth()/2, getMeasuredHeight()/2);
        linearGradient.setLocalMatrix(matrix);
        paint.setShader(linearGradient);
        RectF rect = new RectF(20, 20, getMeasuredWidth() - 20, getMeasuredHeight() - 20);
        canvas.drawArc(rect,0,360,false,paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()), (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()));
    }
}

在这里插入图片描述

改变开始渐变的角度:

  Matrix matrix = new Matrix();
        matrix.setRotate(180, (getMeasuredWidth()-40)/2, (getMeasuredHeight()-40)/2);
        linearGradient.setLocalMatrix(matrix);

positions为null表示线性渐变,如果不为空可以改变渐变中某些颜色的位置。

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(15);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeCap(Paint.Cap.ROUND);
        float[] position = new float[3];
        position[0] = 0.0f;
        position[1] = 0.8f;
        position[2] = 1.0f;

        SweepGradient linearGradient = new SweepGradient(getMeasuredWidth()/2,getMeasuredHeight()/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, position);
       // SweepGradient linearGradient = new SweepGradient((getMeasuredWidth() - 40)/2,(getMeasuredHeight() - 40)/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, null);
        Matrix matrix = new Matrix();
        matrix.setRotate(180, getMeasuredWidth()/2, getMeasuredHeight()/2);
        linearGradient.setLocalMatrix(matrix);
        paint.setShader(linearGradient);
        RectF rect = new RectF(20, 20, getMeasuredWidth() - 20, getMeasuredHeight() - 20);
        canvas.drawArc(rect,0,360,false,paint);
    }

在这里插入图片描述

可以看到蓝色被压缩的只剩了一点。

positions的特殊应用,SweepGradient 无法指定颜色从某个角度到某个角度,可以利用positons指定颜色位置实现相应弧度显示相应颜色。
类似只画半个圆,想让颜色从0度划过90度分布,在90度的位置显示绿色,如果不设置positions则显示效果为:

在这里插入图片描述

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(15);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeCap(Paint.Cap.ROUND);
        float[] position = new float[3];
        position[0] = 0.0f;
        position[1] = 0.25f;
        position[2] = 1.0f;

        SweepGradient linearGradient = new SweepGradient(getMeasuredWidth()/2,getMeasuredHeight()/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, position);
       // SweepGradient linearGradient = new SweepGradient((getMeasuredWidth() - 40)/2,(getMeasuredHeight() - 40)/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, null);
        Matrix matrix = new Matrix();
        matrix.setRotate(180, getMeasuredWidth()/2, getMeasuredHeight()/2);
        linearGradient.setLocalMatrix(matrix);
        paint.setShader(linearGradient);
        RectF rect = new RectF(20, 20, getMeasuredWidth() - 20, getMeasuredHeight() - 20);
        canvas.drawArc(rect,180,90,false,paint);
    }

在这里插入图片描述

基于上面的知识,60度,30度都可以实现。

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(15);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeCap(Paint.Cap.ROUND);
        float[] position = new float[3];
        position[0] = 0.0f;
        position[1] = 0.17f;
        position[2] = 1.0f;

        SweepGradient linearGradient = new SweepGradient(getMeasuredWidth()/2,getMeasuredHeight()/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, position);
       // SweepGradient linearGradient = new SweepGradient((getMeasuredWidth() - 40)/2,(getMeasuredHeight() - 40)/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, null);
        Matrix matrix = new Matrix();
        matrix.setRotate(180, getMeasuredWidth()/2, getMeasuredHeight()/2);
        linearGradient.setLocalMatrix(matrix);
        paint.setShader(linearGradient);
        RectF rect = new RectF(20, 20, getMeasuredWidth() - 20, getMeasuredHeight() - 20);
        canvas.drawArc(rect,180,60,false,paint);
    }

在这里插入图片描述

一个简单的150度圆弧带有渐变:

public class ViewDemo2 extends View {

    public static final int VIEWHEIGHT = 150;
    private int arcWidth = 25;
    private float mProgress = 0f;
    private float mMaxValue = 100;
    private float mCurrentValue  = 0;
    private float startX;
    private float startY;
    private RectF showContent;
    private float mCenterX;
    private float mCenterY;
    private Context mContext;
    private float operationAngle = 150;
    private float mOpenAngle = 150;

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

    public ViewDemo2(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ViewDemo2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    public float getmProgress() {
        return mProgress;
    }

    public void setmProgress(float mProgress) {
        this.mProgress = mProgress;
        requestLayout();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint getPaint = new Paint();
        getPaint.setColor(Color.GREEN);
        getPaint.setStrokeWidth(arcWidth);
        getPaint.setAntiAlias(true);
        getPaint.setStyle(Paint.Style.STROKE);
        getPaint.setStrokeCap(Paint.Cap.ROUND);
        Paint UnGetPaint = new Paint();
        UnGetPaint.setColor(Color.BLACK);
        UnGetPaint.setStrokeWidth(arcWidth);
        UnGetPaint.setAntiAlias(true);
        UnGetPaint.setStyle(Paint.Style.STROKE);
        UnGetPaint.setStrokeCap(Paint.Cap.ROUND);
        float[] position = new float[3];
        mProgress = 0.8f;
        position[0] = 0.0f;
        position[1] = 0.5f*(150*1.0f)/180f * mProgress;
        position[2] = 1.0f;

        SweepGradient linearGradient = new SweepGradient(mCenterX,mCenterY,new int[]{Color.RED,Color.BLUE, Color.GREEN}, position);
       // SweepGradient linearGradient = new SweepGradient((getMeasuredWidth() - 40)/2,(getMeasuredHeight() - 40)/2,new int[]{Color.RED,Color.GREEN, Color.BLUE}, null);
        Matrix matrix = new Matrix();
        matrix.setRotate(190, mCenterX, mCenterY);
        linearGradient.setLocalMatrix(matrix);
        getPaint.setShader(linearGradient);

        canvas.drawArc(showContent,195,150,false,UnGetPaint);
        canvas.drawArc(showContent,195,150 * mProgress,false,getPaint);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        paint.setColor(Color.RED);
        paint.setTextSize(34);
        float radius = (mCenterY - startY)*1.0f;

        try {
            int cutNUm = 3;
            if(mOpenAngle == operationAngle){
                int xuanzhuan = (int) (mOpenAngle/(cutNUm -1));
                int awardText = 0;
                for(int i =0;i<cutNUm;i++ ){
                    int sweeppp = i * xuanzhuan;
                    double bcy = 0;
                    double acx = 0;
                    double posx = 0;
                    double posy = 0;
                    if(sweeppp == 0){
                        posx = arcWidth*2 + 15;
                        posy = (double) mCenterY - 100 - arcWidth;
                        awardText = 0;
                    }else if (sweeppp > 0 && sweeppp < 75){
                        bcy = (double) (radius * Math.sin(sweeppp*1.0/180*Math.PI));
                        acx = (double) (radius * Math.cos(sweeppp*1.0/180*Math.PI));
                        posx = (double) (mCenterX - acx);
                        posy = (double) (mCenterY - bcy);
                        awardText = (int) ((sweeppp / operationAngle) * mMaxValue);
                        Rect rect = new Rect();
                        String awardStr = awardText + "";
                        paint.getTextBounds(awardStr,0,awardStr.length(), rect);
                        int awardwidth = rect.width();
                        int awardheight = rect.height();
                        posy =  posy + awardheight + arcWidth;
                        posx = posx + awardwidth + arcWidth;
                    }else if(sweeppp < operationAngle && sweeppp > 75){
                        int sweep2 = (int) (operationAngle - sweeppp);
                        bcy = (double) (radius * Math.sin(sweep2*1.0/180*Math.PI));
                        acx = (double) ((radius * Math.cos(sweep2*1.0/180*Math.PI)));
                        posx = (double) (mCenterX + acx);
                        posy = (double) (mCenterY - bcy);
                        awardText = (int) ((sweeppp / operationAngle) * mMaxValue);
                        Rect rect = new Rect();
                        String awardStr = awardText + "";
                        paint.getTextBounds(awardStr,0,awardStr.length(), rect);
                        int awardwidth = rect.width();
                        int awardheight = rect.height();
                        posy =  posy + awardheight + arcWidth;
                        posx = posx - awardwidth -arcWidth;
                    }else if(sweeppp == operationAngle){
                        posx = (double)((mCenterX + radius)) ;
                        posy = (double) (mCenterY) - 100 - arcWidth;
                        awardText= (int) mMaxValue;
                        Rect rect = new Rect();
                        String awardStr = awardText + "";
                        paint.getTextBounds(awardStr,0,awardStr.length(), rect);
                        int awardwidth = rect.width();
                        int awardheight = rect.height();
                        posx = posx - awardwidth - arcWidth *2 -3;
                    }else if(sweeppp == 75){
                        posx = (double) mCenterX;
                        posy = (double) ((mCenterY - radius + 10)- arcWidth*2);
                        awardText= (int) (mMaxValue / 2);
                        Rect rect = new Rect();
                        String awardStr = awardText + "";
                        paint.getTextBounds(awardStr,0,awardStr.length(), rect);
                        int awardwidth = rect.width();
                        int awardheight = rect.height();
                        posy =  posy + awardheight + arcWidth*2 + 10;
                        posx = posx - awardwidth/2;
                    }
                    canvas.drawText(awardText+"", (float) posx, (float) posy, paint);

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, VIEWHEIGHT*2, getResources().getDisplayMetrics()), (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, VIEWHEIGHT, getResources().getDisplayMetrics()));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        float edgeLengthWidth;
        float edgeLengthHeight;
        int fix = 0;

        edgeLengthWidth = w - getPaddingRight() - getPaddingLeft() - arcWidth - arcWidth;
        edgeLengthHeight = (h - getPaddingBottom() - getPaddingTop() - arcWidth ) * 2 ;

        startX = getPaddingLeft() + arcWidth;
        startY = getPaddingTop()  + arcWidth;

        // 得到显示区域和中心的
        showContent = new RectF(startX + fix, startY + fix, startX + edgeLengthWidth, startY + edgeLengthHeight);
        mCenterX = showContent.centerX();
        mCenterY = showContent.centerY();

    }

}

在这里插入图片描述

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值