【问题标题】:Android SweepGradientAndroid SweepGradient
【发布时间】:2012-11-15 18:15:46
【问题描述】:

我有一个 SweepGradient 定义为

circle_paint.setShader(new SweepGradient(getWidth()/2, getHeight()/2, new int[] { circle_start_color, circle_end_color}, new float[] { 0f, 1f}))

应用于定义为

的拱门
canvas.drawArc(circle_bounds, circle_start_perc*360f, circle_end_perc*360f, true, circle_paint);

这很好用,但我需要拱门从屏幕顶部开始绘制,即

canvas.drawArc(circle_bounds, ((circle_start_perc*360f)-90f)%360, circle_end_perc*360f, true, circle_paint);

问题是 SweepGradient 似乎仍然从 0 度开始,而我需要它从 270 度开始(类似于弧线图上的平移)。换句话说,如果我有一个从白色到蓝色的渐变,我需要将弧的顶部涂成白色,然后将弧的最后部分涂成蓝色。我该怎么做?

【问题讨论】:

    标签: android android-canvas ondraw gradient


    【解决方案1】:

    使用Matrix.preRotate 旋转 SweepGradient 的原点:

    final int[] colors = {circle_start_color, circle_end_color};
    final float[] positions = {0f, 1f};
    Gradient gradient = new SweepGradient(circle_bounds.centerX(), circle_bounds.centerY(), colors, positions);
    float rotate = 270f;
    Matrix gradientMatrix = new Matrix();        
    gradientMatrix.preRotate(rotate, circle_bounds.centerX(), circle_bounds.centerY());
    gradient.setLocalMatrix(gradientMatrix);
    mPaint.setShader(gradient);
    

    【讨论】:

      【解决方案2】:

      您可以尝试在SweepGradient 上使用getLocalMatrix()setLocalMatrix() 来对着色器应用旋转。您可以获取当前矩阵,使用postRotate() 发布适当的旋转,然后将其设置回着色器元素。

      另一种选择是旋转Canvas。您可以预先旋转画布,绘制内容,然后恢复它;或者先绘制内容,然后旋转画布。

      【讨论】:

      • 谢谢。我只是在画拱门之前旋转了画布,然后恢复了画布,就像一个魅力:)
      • 着色器旋转是一个很好的建议。使您不必像@BOENDAGGER 对save/restore 所做的那样做。只需设置一次着色器旋转即可。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多