2017-08-29 30 views
2

我有一個從URL加載一個位圖,並使用一個調色板來改變我的浮動操作按鈕的背景中的AsyncTask。大多數圖片工作正常,但在某些情況下,它使按鈕透明。截圖1示出了按鈕顏色從圖像但在截圖2的按鈕的顏色藍色工作是透明的(即使圖像犯規包含任何透明像素,因爲它是一個JPEG)。Android的調色板返回透明色一些圖片

public class ColoredFabTask extends AsyncTask<String , String , String> { 
    Context mContext; 
    View view; 
    private View rootView; 
    URL myFileUrl; 
    Bitmap imageBitmap = null; 

    public ColoredFabTask(Context context, View view) { 
     this.mContext = context; 
     this.view = view; 
    } 

    @Override 
    protected void onPreExecute() { 
    } 

    @Override 
    protected String doInBackground(String... args) { 
     try { 
      myFileUrl = new URL(args[0]); 
      HttpURLConnection conn = (HttpURLConnection) 
      myFileUrl.openConnection(); 
      conn.setDoInput(true); 
      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      imageBitmap = BitmapFactory.decodeStream(is); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String args) { 
     Palette palette = Palette.from(imageBitmap).generate(); 
     int vibrant = palette.getVibrantColor(0); 
     FloatingActionButton applyButton = (FloatingActionButton) view.findViewById(R.id.applyButton); 
     applyButton.setBackgroundTintList(ColorStateList.valueOf(vibrant)); 
     applyButton.setVisibility(View.VISIBLE); 
    } 
} 

截圖:

enter image description here

enter image description here

回答

1

固定的問題我自己,如果有人想知道怎麼辦。只要檢查色板是否爲空。

 Palette palette = Palette.from(imageBitmap).generate(); 
     int fallbackColor = palette.getDominantColor(0); 
     Palette.Swatch vibrantColorSwatch = palette.getVibrantSwatch(); 
     if (vibrantColorSwatch != null) { 
      int vibrantColor = vibrantColorSwatch.getRgb(); 
      FloatingActionButton applyButton = (FloatingActionButton) view.findViewById(R.id.applyButton); 
      applyButton.setBackgroundTintList(ColorStateList.valueOf(vibrantColor)); 

     } 
     else { 
      FloatingActionButton applyButton = (FloatingActionButton) view.findViewById(R.id.applyButton); 
      applyButton.setBackgroundTintList(ColorStateList.valueOf(fallbackColor)); 
     } 
1

Paletter忽略了這裏面默認一些顏色。下面是它從調色板源實現:

static final Palette.Filter DEFAULT_FILTER = new Palette.Filter() { 
    private static final float BLACK_MAX_LIGHTNESS = 0.05F; 
    private static final float WHITE_MIN_LIGHTNESS = 0.95F; 

    public boolean isAllowed(int rgb, float[] hsl) { 
     return !this.isWhite(hsl) && !this.isBlack(hsl) && !this.isNearRedILine(hsl); 
    } 

    private boolean isBlack(float[] hslColor) { 
     return hslColor[2] <= 0.05F; 
    } 

    private boolean isWhite(float[] hslColor) { 
     return hslColor[2] >= 0.95F; 
    } 

    private boolean isNearRedILine(float[] hslColor) { 
     return hslColor[0] >= 10.0F && hslColor[0] <= 37.0F && hslColor[1] <= 0.82F; 
    } 
}; 

正如你所看到的,它迫使調色板忽略一些顏色。 所以,你需要嘗試設置自定義過濾器,以便處理所有顏色