2017-09-26 87 views
0

我想將ImageView設置爲SweepGradient。將ImageView設置爲PaintDrawable - Android

這裏是我的嘗試:

protected void onCreate(@Nullable Bundle savedInstanceState) { 

    ImageView colorPicker = findViewById(R.id.color_picker); 
    colorPicker.setImageDrawable(CreateColorPickerDrawable()); 

} 

private PaintDrawable CreateColorPickerDrawable() 
{ 
    int[] colors = {0xFFFF0000, 0xFF00FF00, 0xFF0000FF}; 
    PaintDrawable paintDrawable = new PaintDrawable(); 

    paintDrawable.setCornerRadius(getResources().getDimension(R.dimen.corner_radius)); 

    SweepGradient sweepGradient = new SweepGradient(50, 50, colors, null); 
    paintDrawable.getPaint().setShader(sweepGradient); 

    return paintDrawable; 
} 

但似乎沒有梯度。

我也看到了這一點:Imageview set color filter to gradient

但我想我們有了是比簡單的解決方案(加上它需要一個位圖src和我只是想我的ImageView爲矩形W /圓角角落[這可以很容易地做到/ PaintDrawable])。

如果任何人有任何指導/建議,將不勝感激!泰!

回答

0

我被一個DERP。我只需將ImageView切換到普通視圖,然後我就可以將背景drawable替換爲我的paintDrawable。

protected void onCreate(@Nullable Bundle savedInstanceState) { 

View colorPicker = findViewById(R.id.color_picker); 
colorPicker.setBackground(CreateColorPickerDrawable()); 

} 

private PaintDrawable CreateColorPickerDrawable() { 
int[] colors = {0xFFFF0000, 0xFF00FF00, 0xFF0000FF}; 
PaintDrawable paintDrawable = new PaintDrawable(); 

paintDrawable.setCornerRadius(getResources().getDimension(R.dimen.corner_radius)); 

SweepGradient sweepGradient = new SweepGradient(50, 50, colors, null); 
paintDrawable.getPaint().setShader(sweepGradient); 

return paintDrawable; 
} 
0

如果您需要靜態解決方案,則可以使用可繪製的XML文件。

XML(gradient_1.xml)

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <gradient 
     android:startColor="#aa0000" 
     android:centerColor="#00aa00" 
     android:endColor="#0000aa" 
     android:angle="270"/> 
    <corners android:radius="0dp" /> 
</shape> 

的Java

ImageView imageView = (ImageView) findViewById(R.id.imageViewGradient); 
imageView.setImageResource(R.drawable.gradient_1); 
+0

我最終希望它是動態的,硬編碼的顏色只是爲了測試。對不起,哥們:/ –