- Manipulating images and Drawables with Android’s ColorFilter
- Tinting, custom effects and reusability for visual Android app resources
- Where can this be used? 🤔
- Canvas
- Drawable
- ImageView
- Introducing our sample image 🖼️
- PorterDuffColorFilter 1️⃣
- LightingColorFilter 2️⃣
- ColorMatrixColorFilter 3️⃣
- Limitations and other options 🛠️
- [MaterialButton] Programmatically setting background tint having alpha blends with existing tint rather than replacing #1033
- Comments
- damianw commented Feb 18, 2020
- Как установить оттенок для просмотра изображений программно в Android?
- Как настроить оттенок для просмотра изображений программно в android?
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Ответ 18
- Ответ 19
- Ответ 20
- Ответ 21
- Ответ 22
Manipulating images and Drawables with Android’s ColorFilter
Tinting, custom effects and reusability for visual Android app resources
Image and Drawable resources are an integral part of any Android app. Since day (i.e. API level) 1, the Android framework has provided a means of manipulating the colors of these assets on a per-pixel level, as they are drawn to screen, with the ColorFilter class.
The documentation for the base abstract class stipulates that “a color filter can be used with a Paint to modify the color of each pixel drawn with that paint”. This is a powerful tool that can be used for:
- Applying effects and adjustments to images
- Tinting of icons and logos
Ultimately this encourages the good practice of reusing resources for scenarios that require different color variations, resulting in reduced app size.
Note: ColorFilter is an abstract class that should never be used directly, and the constructor was deprecated in API level 26. Only the subclasses should be used, which we will discuss further down.
Where can this be used? 🤔
Before we explore the existing subclasses and their capabilities, we need to discuss where we can actually use ColorFilter .
Canvas
As hinted at in the documentation description, we can use ColorFilter when drawing to Canvas in a custom View . Specifically, a ColorFilter is set on a Paint which then affects everything that is drawn with it:
Drawable
A ColorFilter can be applied to a Drawable , which will affect how it is rendered in View s and layouts:
In addition to this, there exists a Drawable convenience function to apply a PorterDuffColorFilter (more on that later):
Lastly, it is important to note that a tint can be applied to a Drawable . This is separate and will be overridden if a ColorFilter is set via either one of the above functions.
ImageView
A ColorFilter can be applied to an ImageView , which will affect how its current image will be rendered:
As with Drawable , convenience functions exist for applying a PorterDuffColorFilter :
Introducing our sample image 🖼️
We are now going to dive into the three subclasses of ColorFilter ( PorterDuffColorFilter , LightingColorFilter and ColorMatrixColorFilter ). In order to demonstrate this, we will make use of a visual aid in the form of a sample image:
It has photographic detail while also having “shape” as a result of the transparent areas. This will allow all of the subclasses to be demonstrated.
PorterDuffColorFilter 1️⃣
We have already touched on this briefly. This is a color filter that accepts a single color that is applied to all source pixels along with a Porter-Duff composite mode. There are many modes that are suitable to different scenarios. Typically, this is used to apply a “blanket” color (eg. To tint an icon).
LightingColorFilter 2️⃣
This color filter can be used to simulate lighting effects on an image. The constructor accepts two parameters, the first to multiply the source color ( colorMultiply ) and the second to add to the source color ( colorAdd ).
While the source color alpha channel is not affected, the R, G and B channels are computed like so:
Note: The above is using Android KTX Color extension functions for accessing the red, blue and green channels (alpha is also available).
ColorMatrixColorFilter 3️⃣
This is arguably the most flexible (but also the most complex) color filter.
It is quite similar to LightingColorFilter , in that we can tweak each pixel’s color channels using values that are multiplicative and additive. However, a ColorMatrixColorFilter is constructed with a ColorMatrix , which is essentially a wrapper class for a 4×5 matrix. This gives us 20 values, used in a certain way, that allow us to transform colors using all of the existing channels, including alpha.
Before we dive into using matrices, let’s first take a look at some of the convenience functions offered by ColorMatrix :
Fear not if some of these color concepts do not make sense! The point here is that ColorMatrix offers a lot of flexibility, and these convenience functions are simply matrix operations under the hood.
We know that ColorMatrix wraps a 4×5 matrix. Given this matrix, how do we arrive at our resultant color channels? They are computed like so:
The 4 rows in fact represent the resultant R, G, B and A channels. For each channel, the 5 columns allow you to combine the existing R, G, B, and A channels and a wildcard value in a plethora of ways.
This provides us with a lot of possibilities. We can adjust the brightness/contrast of images, ignore some channels, invert an image or even create basic filters and effects.
Limitations and other options 🛠️
While ColorFilter is powerful and flexible, image manipulation is a vast field and it simply cannot cover everything.
For example, the current pixel value that is being passed through the filter would be handy to know, but is not available. Additionally, you are limited to the three subclasses that ColorFilter currently provides. It appears as if you cannot create a custom subclass, due to native code restrictions.
In instances like this, what other options do we have?
The graphics framework has other useful classes such as Shader and MaskFilter . We could turn to RenderScript , which offers Bitmap utilities that still keep us mostly within traditional Android graphics territory. There is also OpenGL, which is perhaps the most extreme power vs. complexity tradeoff, but opens up all of the possibilities of custom GLSL shaders.
Overall, ColorFilter is still a fantastic tool for working with app resources.
I hope this post has provided some insight into ColorFilter and the flexibility it provides when working with images and Drawable s. If you have any questions, thoughts or suggestions then I’d love to hear from you!
Источник
[MaterialButton] Programmatically setting background tint having alpha blends with existing tint rather than replacing #1033
Comments
damianw commented Feb 18, 2020
Description:
Setting a non-opaque background tint (via setBackgroundTintList ) on a MaterialButton causes the new background tint to blend with the previous background tint, rather than replace it. This is especially noticeable when trying to set a transparent background tint, which has no effect.
Source code: A sample app that reproduces the problem can be found here: https://github.com/damianw/MaterialButtonTransparentTint
Expected behavior:
In the following demo (MainActivity, activity_main.xml), we define a MaterialButton like so:
and change the background tint whenever the button is pressed:
As seen in the demonstration below, clicking the button has no effect:
The issue appears to be that the new color is actually blended with the previous color — an effect that can be confirmed by changing altColor to 0x660000FF (translucent blue). In this demonstration, the new color is purple:
This issue is not present when with either android.widget.Button or androidx.appcompat.widget.AppCompatButton .
Using an altColor of 0x00000000 on an androidx.appcompat.widget.AppCompatButton :
Using an altColor of 0x660000FF (translucent blue) on an androidx.appcompat.widget.AppCompatButton :
Android API version: 29
Material Library version: com.google.android.material:material:1.2.0-alpha04
Device: API 29 Emulator
The text was updated successfully, but these errors were encountered:
Источник
Как установить оттенок для просмотра изображений программно в Android?
Нужно установить оттенок для изображения . Я использую его следующим образом:
Но это не меняет .
Вы можете легко изменить оттенок в коде с помощью:
imageView.setColorFilter(Color.argb(255, 255, 255, 255)); // Белый оттенок
Если вы хотите цветовой оттенок, то
Для векторного Drawable
ОБНОВЛЕНИЕ :
@ADev имеет более новое решение в своем ответе здесь , но его решение требует более новой библиотеки поддержки — 25.4.0 или выше.
Большинство ответов относятся к использованию, setColorFilter а не к тому, что было задано изначально.
Пользователь @Tad имеет свой ответ в правильном направлении, но он работает только на API 21+.
Чтобы установить оттенок на всех версиях Android, используйте ImageViewCompat :
Обратите внимание, что yourTint в этом случае должен быть «цвет int». Если у вас есть такой цветовой ресурс R.color.blue , вам нужно сначала загрузить цвет int:
Это сработало для меня
@ Хардик это правильно. Другая ошибка в вашем коде — это когда вы ссылаетесь на свой определенный XML цвет. Вы прошли только идентификатор к setColorFilter способу, когда вы должны использовать идентификатор , чтобы найти цвет ресурс и передать ресурс к setColorFilter методу. Переписав свой оригинальный код ниже.
Если эта строка находится в вашей деятельности:
Иначе, вам нужно указать свою основную деятельность:
Обратите внимание, что это также относится и к другим типам ресурсов, таким как целые числа, bools, измерения и т. Д. За исключением строки, которую вы можете напрямую использовать getString() в своей Деятельности без необходимости первого вызова getResources() (не спрашивайте меня, почему) ,
В противном случае ваш код выглядит хорошо. (Хотя я не слишком исследовал setColorFilter метод . )
Источник
Как настроить оттенок для просмотра изображений программно в android?
Нужно установить оттенок для представления изображения. Я использую его следующим образом:
Но это не меняется.
ОТВЕТЫ
Ответ 1
Вы можете легко изменить оттенок в коде с помощью:
imageView.setColorFilter(Color.argb(255, 255, 255, 255)); // Белый оттенок
Если вы хотите цветовой оттенок, то
Для векторного Drawable
ОБНОВЛЕНИЕ:
У @ADev есть более новое решение в его ответе здесь, но его решение требует более новой библиотеки поддержки — 25.4.0 или выше.
Ответ 2
Большинство ответов относятся к использованию setColorFilter , который не был изначально задан.
Пользователь @Tad имеет его ответ в правильном направлении, но он работает только с API 21 +.
Чтобы установить оттенок во всех версиях Android, используйте ImageViewCompat :
Обратите внимание, что yourTint в этом случае должен быть «color int». Если у вас есть ресурс цвета, например R.color.blue , сначала нужно сначала загрузить цвет int:
Ответ 3
Это сработало для меня
Ответ 4
@Хардик прав. Другая ошибка в вашем коде — это когда вы ссылаетесь на свой цвет, определенный XML. Вы передали только id методу setColorFilter , когда вы должны использовать идентификатор, чтобы найти ресурс цвета, и передать ресурс методу setColorFilter . Переписывая исходный код ниже.
Если эта строка находится в пределах вашей активности:
Кроме того, вам необходимо указать ваше основное действие:
Обратите внимание, что это также относится к другим типам ресурсов, таким как целые числа, bools, измерения и т.д. За исключением строки, для которой вы можете напрямую использовать getString() в своей деятельности без необходимости сначала звонить getResources() (не спрашивайте меня, почему).
В противном случае ваш код выглядит хорошо. (Хотя я не исследовал метод setColorFilter слишком много. )
Ответ 5
После того, как я пробовал все методы, и они не работали для меня.
Я получаю решение с помощью другого PortDuff.MODE.
Ответ 6
Начиная с леденец, есть также Оттенок метод BitmapDrawables, который работает с новым классом Palette:
public void setTintList (оттенок ColorStateList)
public void setTintMode (PorterDuff.Mode tintMode)
В старых версиях Android теперь вы можете использовать библиотеку DrawableCompat
Ответ 7
Попробуй это. Он должен работать на всех версиях Android, поддерживаемых библиотекой поддержки:
Вы можете использовать любой из вышеперечисленных функций, чтобы заставить его работать.
Вы можете прочитать о более интересных особенностей DrawableCompat на документы, здесь.
Ответ 8
Простая и одна строка
Ответ 9
Начиная с Lollipop существует метод, называемый ImageView#setImageTintList() который вы можете использовать. Преимущество состоит в том, что для него требуется ColorStateList а не только один цвет, что делает отображение ColorStateList в соответствии с цветом.
На устройствах с предустановленной Lollipop вы можете получить такое же поведение, показывая выделение, а затем установите его как графическое изображение ImageView :
Ответ 10
Ответ 11
Поскольку первый ответ не сработал у меня:
Это похоже, похоже, работает в API 21+, но для меня это не проблема. Вы можете использовать ImageViewCompat для решения этой проблемы, tho.
Надеюсь, я помог кому-нибудь: -)
Ответ 12
Если ваш цвет имеет прозрачность шестнадцатеричного цвета, используйте приведенный ниже код.
Чтобы очистить оттенок
Ответ 13
Я обнаружил, что мы можем использовать селектор цвета для оттенка attr:
Ответ 14
Не используйте PoterDuff.Mode , используйте setColorFilter() он работает для всех.
Ответ 15
Как сказал @milosmns, вы должны использовать imageView.setColorFilter(getResouces().getColor(R.color.blue),android.graphics.PorterDuff.Mode.MULTIPLY);
Для этого API требуется значение цвета вместо идентификатора ресурса цвета. Это основная причина, почему ваш оператор не работает.
Ответ 16
Я опаздываю на вечеринку, но я не видел своего решения выше. Мы также можем установить оттенок цвета с помощью setImageResource() (мой minSdkVersion равен 24).
Итак, во-первых, вам нужно создать селектор и сохранить его в папке ресурсов /drawable (я называю это ic_color_white_green_search.xml )
Затем установите его в коде так:
Ответ 17
Добавление к ADev ответа (что на мой взгляд является наиболее правильным), начиная с широкого распространения Kotlin, и его полезных функций расширения:
Я думаю, что эта функция может быть полезна в любом проекте Android!
Ответ 18
Для установки оттенка для просмотра изображений программно в Android
У меня есть два метода для Android:
Я надеюсь, что я помог никому 🙂
Ответ 19
Лучшая упрощенная функция расширения благодаря ADev
Использование:-
Ответ 20
Если вы хотите установить селектор на ваш оттенок:
Ответ 21
Просто добавьте, если вы хотите удалить существующий оттенок, вы можете установить его в прозрачный цвет:
Ответ 22
Неточный ответ, но более простая альтернатива:
- Поместите другой вид поверх изображения
- Измените значение альфа, но вы хотите (программно) получить желаемый эффект.
Источник