2016-11-27 214 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