Android自定义View

SweepGradient扫描渐变的(float cx, flo

2017-11-01  本文已影响0人  仁昌居士

SweepGradient 作为画图时,用到的扫描渐变。
有两个方法。
第一个方法:
public SweepGradient(float cx, float cy, int color0, int color1)

Parameters:

第二个方法:
public SweepGradient(float cx, float cy, int[] colors, float[] positions)

Parameters:

很明显,第一个方法是第二个方法的简化。
所以,我只用讲下面一个方法,就能两个方法都懂了。
查阅了API:

 /**
     * A subclass of 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.
     */

前三个参数很容易理解:

image.png

颜色数组为{"绿色","黑色","红色","蓝色","黄色"},
绿色在180度,所以他对应的位置参数是0.5 (顺时针算)
以此类推,黑色225度,0.625f
红色 270度,0.75f
蓝色315度,0.875f
黄色360度,1
所以对应的positions数组就是{ 0.5f, 0.625f, 0.75f, 0.875f, 1f }

package com.hencoder.hencoderpracticedraw2.practice;

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

public class Practice03SweepGradientView extends View {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public Practice03SweepGradientView(Context context) {
        super(context);
    }

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

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

    {
        // 用 Paint.setShader(shader) 设置一个 SweepGradient
        // SweepGradient 的参数:圆心坐标:(300, 300);颜色:#E91E63 到 #2196F3

        Shader shader = new SweepGradient(300,300, new int[]{ Color.GREEN, Color.BLACK, Color.RED, Color.BLUE,Color.YELLOW},
                new float[]{0.5f, 0.625f, 0.75f, 0.875f, 1f}
        );
        paint.setShader(shader);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(300, 300, 200, paint);
    }
}

这样对第二个更详细的方法,就能理解了,至于第一个就是两种颜色的均匀分布,很好理解。

上一篇 下一篇

猜你喜欢

热点阅读