下面列出了怎么用android.graphics.drawable.Drawable的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Generate label background and foreground colors using Palette base on downloaded image colors.
*
* @param bitmap Download bitmap.
*/
@Override
public void onBitmapChange(Bitmap bitmap) {
if (bitmap == null) { return; }
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
@SuppressWarnings("deprecation")
public void onGenerated(Palette palette) {
Resources res = getResources();
int photoNameColorBg = palette.getDarkMutedColor(res.getColor(R.color.list_item_photo_name_bg));
int photoNameColorFg = palette.getLightMutedColor(res.getColor(R.color.view_photo_name_fg));
ColorFilter photoNameColorFilter = new LightingColorFilter(photoNameColorBg, 1);
Drawable photoNameDrawableBg = res.getDrawable(R.drawable.view_photo_name_bg);
photoNameDrawableBg.setColorFilter(photoNameColorFilter);
mPhotoName.setBackgroundDrawable(photoNameDrawableBg);
mPhotoName.setTextColor(photoNameColorFg);
}
});
}
/**
* update background color based on the current device connectivity
*/
public void updateBackground(boolean isConnected) {
try {
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0f);
final ColorFilter filter = new ColorMatrixColorFilter(cm);
final ColorFilter filterOnline = getOnlineColorFilter();
final View bgView = ImageManager.getWallpaperView();
if (bgView != null) {
final Drawable bgDrawable = bgView.getBackground();
if (bgDrawable != null) {
bgDrawable.setColorFilter(isConnected ? filterOnline : filter);
}
}
if(this instanceof ArcusProductFragment) {
final ArcusProductFragment fragment = (ArcusProductFragment) this;
fragment.setEnabled(isConnected);
}
if(callback != null) {
callback.backgroundUpdated();
}
}catch (Exception e){
logger.error("Can't change background color filter: {}", e);
}
}
@OnMount
static void onMount(
ComponentContext c,
ProgressBar progressBar,
@Prop(optional = true, resType = ResType.COLOR) int color,
@FromPrepare Drawable resolvedIndeterminateDrawable) {
if (resolvedIndeterminateDrawable != null) {
progressBar.setIndeterminateDrawable(resolvedIndeterminateDrawable);
}
if (color != Color.TRANSPARENT && progressBar.getIndeterminateDrawable() != null) {
progressBar
.getIndeterminateDrawable()
.mutate()
.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
}
private void initAttrs(Context context, AttributeSet attr) {
if (attr != null) {
TypedArray typedArray = context.obtainStyledAttributes(attr, R.styleable.CustomDrawableTextView);
drawableWidth = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableWidth, 0);
drawableHeight = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableHeight, 0);
drawableLeftWidth = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableLeftWidth, 0);
drawableLeftHeight = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableLeftHeight, 0);
drawableRightWidth = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableRightWidth, 0);
drawableRightHeight = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableRightHeight, 0);
drawableTopWidth = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableTopWidth, 0);
drawableTopHeight = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableTopHeight, 0);
drawableBottomWidth = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableBottomWidth, 0);
drawableBottomHeight = typedArray.getDimensionPixelOffset(R.styleable.CustomDrawableTextView_t_drawableBottomHeight, 0);
typedArray.recycle();
}
Drawable drawables[] = getCompoundDrawables();
Drawable left = drawables[0];
Drawable top = drawables[1];
Drawable right = drawables[2];
Drawable bottom = drawables[3];
setCompoundDrawables(left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables != null) {
Drawable drawableLeft = drawables[0];
if (drawableLeft != null) {
float textWidth = getPaint().measureText(getText().toString());
int drawablePadding = getCompoundDrawablePadding();
int drawableWidth = 0;
drawableWidth = drawableLeft.getIntrinsicWidth();
float bodyWidth = textWidth + drawableWidth + drawablePadding;
canvas.translate((getWidth() - bodyWidth) / 11 * 5, 0);
}
}
super.onDraw(canvas);
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
}
/**
* 代码跟父类代码相似,就是getCachedDrawable()替换成getDrawable(),因为前者里面的图片是WeakReference,
* 容易被gc回收,所以这里要避免这个问题
*/
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
FontMetricsInt fm) {
Drawable d = getDrawable();
if (lineHeight > 0) {
return (int) (d.getIntrinsicWidth() * scale);
} else {
Rect rect = d.getBounds();
if (fm != null) {
fm.ascent = -rect.bottom;
fm.descent = 0;
fm.top = fm.ascent;
fm.bottom = 0;
}
return rect.right;
}
}
@Override protected void load(Context context) throws Exception {
int newIndex = (oldIndex + 1) % IMAGES.length;
Glide
.with(context)
.load(IMAGES[newIndex])
.fitCenter() // can be implicit, but see thumbnail
.thumbnail(Glide
.with(context)
.load(IMAGES[oldIndex])
.fitCenter() // have to be explicit here to match outer load exactly
)
.listener(new LoggingListener<String, GlideDrawable>() {
@Override public boolean onResourceReady(GlideDrawable resource, String model,
Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
if (isFirstResource) {
return false; // thumbnail was not shown, do as usual
}
return new DrawableCrossFadeFactory<Drawable>(/* customize timings here */)
.build(false, false) // force crossFade() even if coming from memory cache
.animate(resource, (ViewAdapter)target);
}
})
.into(imageView)
;
oldIndex = newIndex;
}
private void buildColorPickerView(View view, int colorCode) {
view.setVisibility(View.VISIBLE);
ShapeDrawable biggerCircle = new ShapeDrawable(new OvalShape());
biggerCircle.setIntrinsicHeight(20);
biggerCircle.setIntrinsicWidth(20);
biggerCircle.setBounds(new Rect(0, 0, 20, 20));
biggerCircle.getPaint().setColor(colorCode);
ShapeDrawable smallerCircle = new ShapeDrawable(new OvalShape());
smallerCircle.setIntrinsicHeight(5);
smallerCircle.setIntrinsicWidth(5);
smallerCircle.setBounds(new Rect(0, 0, 5, 5));
smallerCircle.getPaint().setColor(Color.WHITE);
smallerCircle.setPadding(10, 10, 10, 10);
Drawable[] drawables = {smallerCircle, biggerCircle};
LayerDrawable layerDrawable = new LayerDrawable(drawables);
view.setBackgroundDrawable(layerDrawable);
}
private Bitmap[] generateIconBitmaps(Drawable drawable) {
if (drawable == null)
return null;
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return generateIconBitmaps(Bitmap.createScaledBitmap(bitmap, iconSize, iconSize, false));
}
@Override
public void loadThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView, Uri uri) {
Glide.with(context)
.load(uri)
.asBitmap() // some .jpeg files are actually gif
.placeholder(placeholder)
.override(resize, resize)
.centerCrop()
.into(imageView);
}
private Bitmap drawableToBitamp(Drawable drawable) {
if (drawable != null) {
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
} else {
return null;
}
}
Drawable getIconDrawable() {
if (mIcon != 0) {
return getResources().getDrawable(mIcon);
} else {
return new ColorDrawable(Color.TRANSPARENT);
}
}
private DrawableParent createDrawableParentForIndex(final int index) {
return new DrawableParent() {
@Override
public Drawable setDrawable(Drawable newDrawable) {
return ArrayDrawable.this.setDrawable(index, newDrawable);
}
@Override
public Drawable getDrawable() {
return ArrayDrawable.this.getDrawable(index);
}
};
}
@BindingAdapter({"src", "tintAttr"})
public static void setSrcTintedFromAttr(
@NonNull final ImageView imageView,
@Nullable Drawable src,
@AttrRes final int tintAttr) {
if (src != null) {
src = DrawableUtils
.getTintedDrawableFromAttrTint(imageView.getContext(), src, tintAttr);
}
imageView.setImageDrawable(src);
}
public static ImageSpan createImageSpan(ImageSpan other)
{
Drawable drawable = null;
if (other != null)
drawable = other.getDrawable();
return new ImageSpan(drawable);
}
private void setItemBackground(GradientTabStripItem item) {
if (mItemBackgroundId != NO_ID) {
item.setBackgroundResource(mItemBackgroundId);
} else {
if (mItemBackgroundDrawable != null) {
final Drawable.ConstantState state = mItemBackgroundDrawable.getConstantState();
Drawable background;
if (state != null)
background = state.newDrawable(getResources()).mutate();
else
background = mItemBackgroundDrawable;
item.setBackgroundDrawable(background);
}
}
}
@Nullable
public Drawable getAppIcon(@NonNull PackageInfo packageInfo) {
try {
return mPackageManager.getApplicationIcon(packageInfo.applicationInfo);
} catch (Exception e) {
return mContext.getDrawable(R.drawable.ic_app_icon_unknown);
}
}
public static void applyIconTint(final Drawable app_icon, int mask_color) {
if (Color.alpha(mask_color) > 10) {
app_icon.mutate();
//int avg = (Color.red(mask_color) + Color.green(mask_color) + Color.blue(mask_color) ) / 3;
if (Color.red(mask_color)>5 && Color.red(mask_color) == Color.green(mask_color) && Color.red(mask_color) == Color.blue(mask_color) ) {
setSaturation(app_icon, (255f-Color.red(mask_color))/255f, Color.alpha(mask_color)/255f);
} else {
PorterDuff.Mode mode = PorterDuff.Mode.MULTIPLY;
app_icon.setColorFilter(mask_color, mode);
}
}
}
public BaseViewHolder setCompoundDrawables(@IdRes int id,
@Nullable Drawable left,
@Nullable Drawable top,
@Nullable Drawable right,
@Nullable Drawable bottom) {
View view = findViewById(id);
if (view instanceof TextView)
((TextView) view).setCompoundDrawables(left, top, right, bottom);
return this;
}
@Override
public void loadThumbnail(Context context, int resize, Drawable placeholder, ImageView imageView, Uri uri) {
Glide.with(context)
.asBitmap() // some .jpeg files are actually gif
.load(uri)
.apply(new RequestOptions()
.override(resize, resize)
.placeholder(placeholder)
.centerCrop())
.into(imageView);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
Drawable top = getCompoundDrawables()[1];
if (top instanceof PreloadIconDrawable) {
((PreloadIconDrawable) top).applyTheme(getPreloaderTheme());
}
mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
public static Drawable loadPackageIcon(Context context, String authority, int icon) {
if (icon != 0) {
if (authority != null) {
final PackageManager pm = context.getPackageManager();
final ProviderInfo info = pm.resolveContentProvider(authority, 0);
if (info != null) {
return pm.getDrawable(info.packageName, icon, info.applicationInfo);
}
} else {
return ContextCompat.getDrawable(context, icon);
}
}
return null;
}
public static AvatarWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getAvatarWorkerTask();
}
}
return null;
}
public static void resetDrawableBackgroundColor(@NonNull final View view) {
final int transparentColor = ContextCompat.getColor(view.getContext(), R.color.px_transparent);
final Drawable background = view.getBackground();
if (background != null) {
background.setColorFilter(transparentColor, PorterDuff.Mode.SRC);
}
}
@Override public void setBackgroundColor(int backgroundColor) {
super.setBackgroundColor(backgroundColor);
Drawable background = makeBackground(getResources(), backgroundColor);
background.setBounds(0, 0, root.getWidth(), root.getHeight());
root.setBackground(background);
boolean dark = ColorPreference.isColorDark(backgroundColor);
if (!has(BACKGROUND)) {
setTextColor((dark) ? Color.WHITE : Color.BLACK);
}
}
private void setIcon(int icon) {
Drawable drawable = getResources().getDrawable(icon);
if (drawable != null) {
int padding = (getWidth() / 2) - (drawable.getIntrinsicWidth() / 2);
setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
setPadding(padding, 0, 0, 0);
}
}
private Drawable zoomDrawable(Drawable drawable, int w, int h) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap oldbmp = drawableToBitmap(drawable);
Matrix matrix = new Matrix();
float scaleWidth = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(null, newbmp);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mImageView != null) {
Drawable d = mImageView.getDrawable();
if (d instanceof StateListDrawable) {
StateListDrawable sld = (StateListDrawable) d;
sld.setState(getDrawableState());
sld.invalidateSelf();
}
}
}
@Override
public void bindData(Object obj, int position) {
MyChatMsg data = (MyChatMsg) obj;
TextView textView = (TextView) getView(R.id.tv_activity_news);
Drawable drawableLeft = ContextCompat.getDrawable(AppUtils.getContext(), R.drawable.ic_activity);
Drawable drawableRight = ContextCompat.getDrawable(AppUtils.getContext(), R.drawable.ic_arrow);
if (drawableLeft != null) {
drawableLeft.setBounds(0, 0, DensityUtils.dp2px(AppUtils.getContext(), 18), DensityUtils.dp2px(AppUtils.getContext(), 18));
}
if (drawableRight != null) {
drawableRight.setBounds(0, 0, DensityUtils.dp2px(AppUtils.getContext(), 12), DensityUtils.dp2px(AppUtils.getContext(), 12));
}
textView.setCompoundDrawables(drawableLeft, null, drawableRight, null);
textView.setText(data.activityNews);
}