【问题标题】:SweepGradient change position of start and end colorSweepGradient 改变开始和结束颜色的位置
【发布时间】:2016-11-27 10:54:01
【问题描述】:

我想创建一个具有 底部 -> 左侧 -> 顶部 -> 右侧的渐变的 CircleView。
所以我像这样使用SweepGradient 的画布

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();

    int[] colors = {Color.GREEN, Color.RED};
    float[] positions = {0, 1};

    SweepGradient gradient = new SweepGradient(100, 100, colors, positions);
    paint.setShader(gradient);
    canvas.drawCircle(100, 100, 100, paint);
}

但默认顺序是 right -> bottom -> left -> top 但我想要 bottom -> left -> top -> right 我已经尝试将位置更改为

float[] positions = {0.25f, 1.25f};

但它只适用于AndroidStudio的Preview,当我在真实设备上运行时,它显示的结果与positions = {0, 1}相同

我怎样才能使SweepGradient 像这样从bottom -> left -> top -> right 渐变

--- 更新 --- 我们可以使用setLocalMatrixSweepGradient 像这样旋转渐变

Matrix matrix = new Matrix();
matrix.setRotate(90, 100, 100);
gradient.setLocalMatrix(matrix);

【问题讨论】:

  • 使用Shader#setLocalMatrix(Matrix localM)
  • @pskink 不幸的是,setLocalMatrix 只能在预览模式下完美运行,在我的真实设备 API 19 中它无法运行
  • 然后发布您的代码
  • @pskink 我已经更新了我的代码和真实设备的屏幕截图
  • @pskink 我发现了问题,setRotate(90) 在真实设备中不起作用,但 setRotate(90,100,100);工作。非常感谢

标签: android canvas sweepgradient


【解决方案1】:

在画圆之前旋转画布。

public class CircleView extends View {
    private Paint paint;

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        paint = new Paint();

        int[] colors = {Color.GREEN, Color.RED};
        float[] positions = {0, 1};
        SweepGradient gradient = new SweepGradient(100, 100, colors, positions);
        paint.setShader(gradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.rotate(90, 100, 100);
        canvas.drawCircle(100, 100, 100, paint);
        canvas.restore();
    }
}

Edit-1:
@pkskink 建议的替代方法是使用 setLocalMatrix,如下所示:

public void init() {      
    int[] colors = {Color.GREEN, Color.RED};
    float[] positions = {0, 1};

    Matrix matrix = new Matrix();
    matrix.postRotate(90, 100, 100);

    Shader gradient = new SweepGradient(100, 100, colors, positions);
    gradient.setLocalMatrix(matrix);

    paint = new Paint();
    paint.setShader(gradient);
}

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

【讨论】:

  • 你知道不旋转画布的另一种方法吗?现在在我的项目中,在我创建 SweepGradient 之后,我需要将其设置为 ARC 搜索栏 (github.com/neild001/SeekArc) 的背景。对于圆形,我们可以旋转,但对于 ARC 搜索栏,我们不能旋转
  • 对不起@PhanVanLinh 我不知道其他方式,但请为上述问题创建一个单独的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多