下面列出了android.graphics.drawable.Drawable#setColorFilter() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void handlerPressed(boolean pressed) {
if (pressed) {
Drawable drawable = getDrawable();
if (drawable != null) {
// drawable.mutate().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
ViewCompat.postInvalidateOnAnimation(this);
}
} else {
Drawable drawableUp = getDrawable();
if (drawableUp != null) {
// drawableUp.mutate().clearColorFilter();
drawableUp.clearColorFilter();
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWindowFlags();
setContentView(getLayoutResource());
ButterKnife.inject(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
if (showUpButton()) {
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.icons), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
}
else {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
}
}
}
public static void setEdgeEffectColor(final EdgeEffect edgeEffect, @ColorRes final int color) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
edgeEffect.setColor(color);
return;
}
final Field edgeField = EdgeEffect.class.getDeclaredField("mEdge");
final Field glowField = EdgeEffect.class.getDeclaredField("mGlow");
edgeField.setAccessible(true);
glowField.setAccessible(true);
final Drawable edge = (Drawable) edgeField.get(edgeEffect);
final Drawable glow = (Drawable) glowField.get(edgeEffect);
edge.setColorFilter(color, PorterDuff.Mode.SRC_IN);
glow.setColorFilter(color, PorterDuff.Mode.SRC_IN);
edge.setCallback(null); // free up any references
glow.setCallback(null); // free up any references
} catch (final Exception ignored) {
ignored.printStackTrace();
}
}
protected void onTileReadyToDraw(final Canvas c, final Drawable currentMapTile, final Rect tileRect) {
currentMapTile.setColorFilter(currentColorFilter);
currentMapTile.setBounds(tileRect.left, tileRect.top, tileRect.right, tileRect.bottom);
final Rect canvasRect = getCanvasRect();
if (canvasRect == null) {
currentMapTile.draw(c);
return;
}
// Check to see if the drawing area intersects with the minimap area
if (!mIntersectionRect.setIntersect(c.getClipBounds(), canvasRect)) {
return;
}
// Save the current clipping bounds
c.save();
// Clip that area
c.clipRect(mIntersectionRect);
// Draw the tile, which will be appropriately clipped
currentMapTile.draw(c);
c.restore();
}
private void setCursorColor(EditText view, @ColorInt int color) {
try {
// Get the cursor resource id
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(view);
// Get the editor
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(view);
// Get the drawable and set a color filter
Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
if (drawable != null) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Drawable[] drawables = {drawable, drawable};
// Set the drawables
field = editor.getClass().getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editor, drawables);
} catch (Exception ignored) {
}
}
private static Drawable getPressedStateDrawable(Context context, @PressedMode.Mode int mode, @FloatRange(from = 0.0f, to = 1.0f) float alpha, @NonNull Drawable pressed) {
//ColorDrawable is not supported on 4.4 because the size of the ColorDrawable can not be determined unless the View size is passed in
if (isKitkat() && !(pressed instanceof ColorDrawable)) {
return kitkatDrawable(context, pressed, mode, alpha);
}
switch (mode) {
case PressedMode.ALPHA:
pressed.setAlpha(convertAlphaToInt(alpha));
break;
case PressedMode.DARK:
pressed.setColorFilter(alphaColor(Color.BLACK, convertAlphaToInt(alpha)), PorterDuff.Mode.SRC_ATOP);
break;
default:
pressed.setAlpha(convertAlphaToInt(alpha));
}
return pressed;
}
public static void setCursorColor(EditText editText, int color) {
try {
final Field drawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
drawableResField.setAccessible(true);
final Drawable drawable = getDrawable(editText.getContext(), drawableResField.getInt(editText));
if (drawable == null) {
return;
}
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
final Object drawableFieldOwner;
final Class<?> drawableFieldClass;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
drawableFieldOwner = editText;
drawableFieldClass = TextView.class;
} else {
final Field editorField = TextView.class.getDeclaredField("mEditor");
editorField.setAccessible(true);
drawableFieldOwner = editorField.get(editText);
drawableFieldClass = drawableFieldOwner.getClass();
}
final Field drawableField = drawableFieldClass.getDeclaredField("mCursorDrawable");
drawableField.setAccessible(true);
drawableField.set(drawableFieldOwner, new Drawable[] {drawable, drawable});
} catch (Exception ignored) {
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem undo = menu.findItem(R.id.undo_menu);
MenuItem redo = menu.findItem(R.id.redo_menu);
Drawable iconUndo = ContextCompat.getDrawable(activity, R.drawable.ic_undo_white_36dp);
Drawable iconRedo = ContextCompat.getDrawable(activity, R.drawable.ic_redo_white_36dp);
if (mCanvas.getLinesCount() == 0) {
iconUndo.setColorFilter(ContextCompat.getColor(activity, R.color.theme_default_primary_light),
PorterDuff.Mode.SRC_IN);
} else {
iconUndo.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
}
if (mCanvas.getUndoneLinesCount() == 0) {
iconRedo.setColorFilter(ContextCompat.getColor(activity, R.color.theme_default_primary_light),
PorterDuff.Mode.SRC_IN);
} else {
iconRedo.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
}
undo.setIcon(iconUndo);
redo.setIcon(iconRedo);
}
public static Bitmap flattenExtensionIcon(Drawable baseIcon, int color) {
if (baseIcon == null) {
return null;
}
Bitmap outBitmap = Bitmap.createBitmap(EXTENSION_ICON_SIZE, EXTENSION_ICON_SIZE,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outBitmap);
baseIcon.setBounds(0, 0, EXTENSION_ICON_SIZE, EXTENSION_ICON_SIZE);
baseIcon.setColorFilter(color,
PorterDuff.Mode.SRC_IN);
baseIcon.draw(canvas);
baseIcon.setColorFilter(null);
baseIcon.setCallback(null); // free up any references
return outBitmap;
}
/**
* Returns the icon for permissions that have been disabled by Chrome.
*/
private Drawable getDisabledInChromeIcon(int contentType) {
Drawable icon = ApiCompatibilityUtils.getDrawable(getResources(),
ContentSettingsResources.getIcon(contentType));
icon.mutate();
int disabledColor = ApiCompatibilityUtils.getColor(getResources(),
R.color.primary_text_disabled_material_light);
icon.setColorFilter(disabledColor, PorterDuff.Mode.SRC_IN);
return icon;
}
private static @NonNull CharSequence buildBlessedBadge(@NonNull Context context) {
SpannableString badgeSpan = new SpannableString(" ");
Drawable badge = ContextCompat.getDrawable(context, R.drawable.ic_check_circle_white_18dp);
badge.setBounds(0, 0, badge.getIntrinsicWidth(), badge.getIntrinsicHeight());
badge.setColorFilter(ContextCompat.getColor(context, R.color.core_ultramarine), PorterDuff.Mode.MULTIPLY);
badgeSpan.setSpan(new ImageSpan(badge), 1, badgeSpan.length(), 0);
return badgeSpan;
}
/**
* Tint a menu item
*
* @param menuItem the menu item
* @param color the color
*/
public static void tint(@NonNull MenuItem menuItem, @ColorInt int color) {
Drawable icon = menuItem.getIcon();
if (icon != null) {
icon.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
} else {
throw new IllegalArgumentException("Menu item does not have an icon");
}
}
private void changeFavoriteIcon(ImageView ivFavorite, TreeSet<String> favorites, String objectId) {
Drawable drawable = ivFavorite.getDrawable();
if (favorites.contains(objectId)) {
drawable.setColorFilter(Color.parseColor("#ff0000"), PorterDuff.Mode.SRC_IN);
ivFavorite.setImageDrawable(drawable);
} else {
ivFavorite.setImageResource(R.drawable.ic_favorite);
}
}
/**
* 设置滤镜
*/
private void setFilter() {
//先获取设置的src图片
Drawable drawable=getDrawable();
//当src图片为Null,获取背景图片
if (drawable==null) {
drawable=getBackground();
}
if(drawable!=null){
//设置滤镜
drawable.setColorFilter(Color.GRAY,PorterDuff.Mode.MULTIPLY);;
}
}
/**
* 设置MENU图标颜色
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
int primaryTextColor = MaterialValueHelper.getPrimaryTextColor(this, ColorUtil.isColorLight(ThemeStore.primaryColor(this)));
for (int i = 0; i < menu.size(); i++) {
Drawable drawable = menu.getItem(i).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(primaryTextColor, PorterDuff.Mode.SRC_ATOP);
}
}
return super.onCreateOptionsMenu(menu);
}
public static Drawable setColorFilter(Drawable targetIv) {
if (PreferenceManager.getDefaultSharedPreferences(LNReaderApplication.getInstance().getApplicationContext()).getBoolean(Constants.PREF_INVERT_COLOR, true)) {
targetIv.setColorFilter(Constants.COLOR_UNREAD, Mode.SRC_ATOP);
} else {
targetIv.setColorFilter(Constants.COLOR_UNREAD_DARK, Mode.SRC_ATOP);
}
return targetIv;
}
public void setTopImage(int resId) {
if (resId == 0) {
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
} else {
Drawable drawable = getContext().getResources().getDrawable(resId).mutate();
if (drawable != null) {
drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_emptyListPlaceholder), PorterDuff.Mode.MULTIPLY));
}
textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
textView.setCompoundDrawablePadding(AndroidUtilities.dp(1));
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onPlayStateChanged(Pair<MediaMetadataCompat, PlaybackStateCompat> mediaInfo) {
if (!created) return;
super.onPlayStateChanged(mediaInfo);
LOGI(TAG, "onPlayStateChanged()");
// if (mMusicActive) transition.beginDelayedTransition(mediaContainer, TransitionCompat.KEY_AUDIO_TRANSITION);
// Update button visibility based on the transport flags.
/*if (null == info || info.mTransportControlFlags <= 0) {
mBtnNext.setVisibility(View.VISIBLE);
mBtnPrev.setVisibility(View.VISIBLE);
playPause.setVisibility(View.VISIBLE);
} else {
final int flags = info.mTransportControlFlags;
setVisibilityBasedOnFlag(mBtnPrev, flags, RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS);
setVisibilityBasedOnFlag(mBtnNext, flags, RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
setVisibilityBasedOnFlag(playPause, flags,
RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_STOP);
}*/
// If we have album art, use it!
if (mMusicActive) {
Bitmap albumArtBitmap = mediaInfo.first.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
if (null != albumArtBitmap) {
LOGI(TAG, "Loading artwork bitmap.");
albumArt.setImageAlpha(0xFF);
albumArt.setColorFilter(null);
albumArt.setImageBitmap(albumArtBitmap);
hasAlbumArt = true;
} else {
hasAlbumArt = false;
}
}
// Next, we'll try to display the app's icon.
if (mMusicActive && !hasAlbumArt && !TextUtils.isEmpty(musicPackageName)) {
Drawable appIcon = getAppIcon(musicPackageName);
if (null != appIcon) {
LOGI(TAG, "Loading app icon instead of album art.");
final int bbColor = getResources().getColor(R.color.bb_icons);
final ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
albumArt.setColorFilter(new ColorMatrixColorFilter(cm));
appIcon.setColorFilter(bbColor, PorterDuff.Mode.MULTIPLY);
albumArt.setImageAlpha(0xEF);
albumArt.setImageDrawable(appIcon);
hasAlbumArt = true;
} else {
hasAlbumArt = false;
}
}
if (!mMusicActive) hasAlbumArt = false;
albumArtContainer.setVisibility((hasAlbumArt) ? View.VISIBLE : View.GONE);
if (mMusicActive) setMusicPanelVisibility(View.VISIBLE);
if (!mMusicActive) {
hideMusicWithPanel = true;
}
updatePlayState();
String sTitle = mediaInfo.first.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
String sArtist = mediaInfo.first.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
song.setText(sTitle);
artist.setText(sArtist);
}
/**
* Setup drawables and click listeners based on the {@link ServiceType}
* @param serviceType
*/
private void setupDrawables(ServiceType serviceType, boolean isMove) {
switch (serviceType) {
case COPY:
// if (mainActivity.getAppTheme().equals(AppTheme.DARK)) {
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_content_copy_white_36dp));
// } else {
Drawable drawable = getResources().getDrawable(R.drawable.ic_content_copy_white_36dp);
drawable.setColorFilter(Constants.TEXT_COLOR, PorterDuff.Mode.SRC_IN);
mProgressImage.setImageDrawable(drawable);
//}
mProgressTypeText.setText(isMove ? getResources().getString(R.string.moving)
: getResources().getString(R.string.copying));
cancelBroadcast(new Intent(CopyService.TAG_BROADCAST_COPY_CANCEL));
break;
// case EXTRACT:
// if (mainActivity.getAppTheme().equals(AppTheme.DARK)) {
//
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_zip_box_white_36dp));
// } else {
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_zip_box_grey600_36dp));
// }
// mProgressTypeText.setText(getResources().getString(R.string.extracting));
// cancelBroadcast(new Intent(ExtractService.TAG_BROADCAST_EXTRACT_CANCEL));
// break;
case COMPRESS:
//if (mainActivity.getAppTheme().equals(AppTheme.DARK)) {
drawable = getResources()
.getDrawable(R.drawable.ic_zip_box_white_36dp);
drawable.setColorFilter(Constants.TEXT_COLOR, PorterDuff.Mode.SRC_IN);
mProgressImage.setImageDrawable(drawable);
// } else {
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_zip_box_white_36dp));
// }
mProgressTypeText.setText(getResources().getString(R.string.compressing));
cancelBroadcast(new Intent(ZipTask.KEY_COMPRESS_BROADCAST_CANCEL));
break;
case ENCRYPT:
//if (mainActivity.getAppTheme().equals(AppTheme.DARK)) {
drawable = getResources()
.getDrawable(R.drawable.ic_folder_lock_white_36dp);
drawable.setColorFilter(Constants.TEXT_COLOR, PorterDuff.Mode.SRC_IN);
mProgressImage.setImageDrawable(drawable);
// } else {
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_folder_lock_white_36dp));
// }
mProgressTypeText.setText(getResources().getString(R.string.crypt_encrypting));
cancelBroadcast(new Intent(EncryptService.TAG_BROADCAST_CRYPT_CANCEL));
break;
case DECRYPT:
//if (mainActivity.getAppTheme().equals(AppTheme.DARK)) {
drawable = getResources()
.getDrawable(R.drawable.ic_folder_lock_open_white_36dp);
drawable.setColorFilter(Constants.TEXT_COLOR, PorterDuff.Mode.SRC_IN);
mProgressImage.setImageDrawable(drawable);
// } else {
// mProgressImage.setImageDrawable(getResources()
// .getDrawable(R.drawable.ic_folder_lock_open_white_36dp));
// }
mProgressTypeText.setText(getResources().getString(R.string.crypt_decrypting));
cancelBroadcast(new Intent(EncryptService.TAG_BROADCAST_CRYPT_CANCEL));
break;
}
}
private void updateToolbarConfigs() {
ActionBar actionBar = getSupportActionBar();
if (toolbar == null || actionBar == null) {
return;
}
@ColorInt int primaryColor = Color.parseColor(widgetInfo.getPrimaryColor());
@ColorInt int titleTextColor = Color.parseColor(widgetInfo.getBackgroundColor());
@ColorInt int navigationIconColor = titleTextColor;
@ColorInt int primaryDarkColor = calculatePrimaryDarkColor(primaryColor);
// setup colors (from widget or local config)
if (shouldUseWidgetConfig()) {
setStatusBarColor(primaryDarkColor);
} else {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getTheme();
// toolbar background color
theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
if (typedValue.data != 0) primaryColor = typedValue.data;
// titleFromRes text color
theme.resolveAttribute(R.attr.titleTextColor, typedValue, true);
if (typedValue.data != 0) titleTextColor = typedValue.data;
// back arrow color
theme.resolveAttribute(R.attr.colorControlNormal, typedValue, true);
if (typedValue.data != 0) navigationIconColor = typedValue.data;
theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
if (typedValue.data != 0) primaryDarkColor = typedValue.data;
}
// set colors to views
try {
progressBar.getIndeterminateDrawable().setColorFilter(primaryDarkColor, PorterDuff.Mode.SRC_IN);
} catch (Exception ignored) {
}
toolbar.setBackgroundColor(primaryColor);
String title = inAppChatViewSettingsResolver.getChatViewTitle();
if (StringUtils.isBlank(title)) {
title = widgetInfo.getTitle();
}
actionBar.setTitle(title);
toolbar.setTitleTextColor(titleTextColor);
Drawable drawable = toolbar.getNavigationIcon();
if (drawable != null) {
drawable.setColorFilter(navigationIconColor, PorterDuff.Mode.SRC_ATOP);
}
}