2017-08-29 64 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; 
    } 
}; 

正如你所看到的,它迫使调色板忽略一些颜色。 所以,你需要尝试设置自定义过滤器,以便处理所有颜色