2016-11-27 212 views
1

我想创建一个CircleView,梯度从底部 - >左侧 - >顶部 - >右侧
所以我用帆布SweepGradient这样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); 
} 

enter image description here

但这个默认顺序是右键 - >下 - >左转 - >顶但我想底部 - >左转 - >顶 - >右键 我曾尝试改变位置以

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

,但它只是在AndroidStudio的Preview的作品,当我在真实的设备上运行时,它显示的结果一样positions = {0, 1}

我怎样才能让SweepGradient梯度bottom -> left -> top -> right这样

enter image description here

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

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

enter image description here

+0

使用'着色#setLocalMatrix(矩阵localM)' – pskink

+0

@pskink遗憾的是,仅'setLocalMatrix'工作完美的预览模式,在我的真实设备API 19它不会工作 –

+0

发布您的代码然后 – pskink

回答

2

在绘制圆之前旋转画布。

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(); 
    } 
} 

编辑-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); 
} 
+0

你知道另一种方式去做,而不用旋转画布。在我的项目中,在创建'SweepGradient'后,我需要将它设置为ARC搜索栏的背景(https://github.com/neild001/SeekArc)。我们可以旋转圆形,但对于ARC搜索栏,我们无法旋转 –

+0

对不起@PhanVanLinh我不知道其他方式,但请为上述问题创建一个单独的帖子。 – blizzard