目录

colorFilter-based Image Filter Effect

Overview

In beauty app development, image processing and beautification features have become key elements for improving user experience. By adjusting color filters of original images with different parameters, you can create complex and diverse filter effects for beautifying images.

The ArkUI framework provides the colorFilter attribute in the Image component, which is the core for implementing the image filter effect. It allows you to manipulate the color channels of pixels using a mathematical matrix or underlying graphics objects.

This topic describes how to use the colorFilter attribute to implement common filter effects such as retro, color inversion, saturation enhancement, and skin whitening based on the original image. It also provides detailed explanations of the 4 x 5 RGBA conversion matrix and color filter usage modes of colorFilter, and offers optimization suggestions and FAQs.

How to Implement

The colorFilter attribute is essentially a linear transformation of the RGBA channels of a pixel. This transformation is usually performed in the fragment shader stage of the rendering pipeline, and finally affects the color result of the rendering output. The ArkUI framework provides a 4 × 5 RGBA transformation matrix and color filter to implement this transformation.

The fragment shading stage of the rendering pipeline is a key step in computer graphics processing, which is responsible for calculating the final color of each pixel on the screen.

[h2]4 × 5 RGBA Transformation Matrix

The color matrix is a common method in the industry. It is implemented by passing a 4 x 5 RGBA conversion matrix through colorFilter. This matrix is the core of implementing the image filter effect. Mathematically, this is a 4 × 5 two-dimensional matrix. However, in the ArkTS API implementation, the matrix needs to be expanded by row priority and encapsulated into a one-dimensional array (in number[] format) containing 20 values. The first five elements of the array correspond to the first row (R channel transformation) of the matrix, the next five elements correspond to the second row (G channel transformation), and so on.

Mathematical semantics of the color matrix

In graphics, a pixel consists of four channels: red, green, blue, and alpha (RGBA). The defined formula of the color transformation matrix is as follows:

Relevant parameters need to be set as follows:

Detailed analysis of color transformation matrix parameters

To construct a desired filter effect, you need to understand the meaning of each position in the matrix.

Row Output Channel Formulas
Row 0 Red (Red')
Row 1 Green (Green')
Row 2 Blue (Blue')
Row 3 Transparency (Alpha')

[h2]Color Filter

Since API version 12, ArkUI has opened up the color filter in the @ohos.graphics.drawing module (the DrawingColorFilter API type, which is an alias of the ColorFilter type). Methods that use color filters as parameters implement filter creation in a more advanced, semantic, and simple way. You can specify the color value in ARGB format (see the following description) based on the filter effect to be implemented, and select the preset BlendMode blending mode to create a color filter, so as to implement color filter effects under different blending algorithms.

In HarmonyOS development, ARGB and RGBA are two different color channel sequences.

  • They are essentially the same: Both contain the red, green, blue, and alpha channels.
  • Their usage scenarios are different in the following aspects:
    • ARGB is often used to represent colors in hexadecimal and common2D.Color formats (for example, #FFFF0000 and { alpha: 255, red: 255, green: 0, blue: 0 } both represent opaque red), which is a common format for color resources in HarmonyOS development.
    • RGBA is often used in CSS styles, SVG parsing, and API parameters (for example, rgba(r, g, b, a)). The color matrix calculation of the Image component in ArkUI depends on the normalized RGBA values.

[h2]Differences and Application Scenarios of the Color Transformation Matrix and Color Filter

Dimension Color Transformation Matrix Color Filter (Using createBlendModeColorFilter)
Core Principles 4 × 5 transformation matrix linearly transforms the RGB/Alpha values of pixels. The source image and target image are blended based on blending rules.
Scenario It is suitable for fine parameter control (such as brightness and saturation) and special color transformation in image editing, which is flexible and controllable as well as supports linear transformation. It is suitable for simple UI coloring, overlay, and masking scenarios.

Filter Implementation

[h2]Displaying the Original Image and Initializing the Unit Matrix

In the filter list, the first option is usually the original image or no effect. In terms of technical implementation, the unit matrix is used to correspond to this option.

Color transformation matrix definition:

export const ORIGINAL_MATRIX: number[] = [
  1, 0, 0, 0, 0,
  0, 1, 0, 0, 0,
  0, 0, 1, 0, 0,
  0, 0, 0, 1, 0
];

Principle analysis:

This is a standard unit matrix. According to the matrix multiplication principle, it does not change any RGBA value of the pixel, thereby keeping the original image effect or resetting the image.

The following figure shows the preview.

[h2]Implementing the Retro Grayscale Filter

Color transformation matrix definition:

const RETRO_COLOR_MATRIX: number[] = [
  0.213, 0.715, 0.072, 0, 0,
  0.213, 0.715, 0.072, 0, 0,
  0.213, 0.715, 0.072, 0, 0,
  0, 0, 0, 1, 0
];

Principle analysis:

The following uses a pure color image as an example to describe how to implement the grayscale filter.

Assume that the RGBA color value of the original image is rgba(255, 255, 0, 255), that is, the original [R, G, B, A]. The color transformation matrix is RETRO_COLOR_MATRIX defined above.

According to the defined formula, the following can be calculated:

R' = 0.213 × 255 + 0.715 × 255 + 0.072 × 0 + 0 × 255 + 0 × 255 = 236.64 (red),

G' = 0.213 × 255 + 0.715 × 255 + 0.072 × 0 + 0 × 255 + 0 × 255 = 236.64 (green),

B' = 0.213 × 255 + 0.715 × 255 + 0.072 × 0 + 0 × 255 + 0 × 255 = 236.64 (blue),

A' = 0 × 255 + 0 × 255 + 0 × 0 + 1 × 255 + 0 × 255 = 255 (transparency).

The transformed pixel color component (rounded) is rgba(237, 237, 237, 255).

The following figure shows the preview.

[h2]Implementing the Color Inversion Filter

Color transformation matrix definition:

const REVERSE_COLOR_MATRIX: number[] = [
  -1, 0, 0, 0, 1,
  0, -1, 0, 0, 1,
  0, 0, -1, 0, 1,
  0, 0, 0, 1, 0
];

Principle analysis:

Final effect

[h2]Implementing the Saturation Enhancement Filter

Color transformation matrix definition:

const ENHANCE_COLOR_MATRIX: number[] = [
  1.63, -0.5723, -0.0577, 0, 0,
  -0.17, 1.2277, -0.0577, 0, 0,
  -0.17, -0.5723, 1.7423, 0, 0,
  0, 0, 0, 1, 0
];

Principle analysis:

Description of diagonal values:

  • Core algorithm: Based on the linear interpolation principle, weighted mixing is performed between the grayscale image and the original image. The formula is as follows:

    S indicates the saturation coefficient. In this example, S ≈ 1.8, which means that the saturation is increased by about 80%. Gray indicates the luminance value of a pixel. It is calculated based on the luminance calculation formula in the ITU-R BT.709 international criterion (high definition video color space criterion). For details about the formula, see the principle analysis in the section Implementing the Retro Grayscale Filter.

  • Coefficient derivation: The main diagonal element (1.63) of the red channel is used as an example.
    • Formula expansion:

    • Combined coefficient:

  • Effect: The matrix calculated by the formula retains the luminance information of the image and significantly enhances the differences between the R, G, and B channels, achieving a bright and transparent color effect.

The following figure shows the preview.

[h2]Implementing the Whitening Filter

Color filter definition:

const WHITENING_COLOR_CONFIG: common2D.Color = {
  alpha: 30,
  red: 255,
  green: 255,
  blue: 255
};

const WHITENING_COLOR_FILTER =
  drawing.ColorFilter.createBlendModeColorFilter(WHITENING_COLOR_CONFIG, drawing.BlendMode.PLUS);

Principle analysis:

The following figure shows the preview.

How to Develop

  1. Define a filter data structure.

    Define the image filter option API for easy management and extension.

    export interface FilterOption {
      label: string;
      value: string;
      filter: ColorFilter | number[];
    }
  2. Initialize the filter configuration.

    Define filter matrices and filter option lists in the component.

    • For details about the filter matrix definition, see Filter Implementation.

    • A filter option list is defined as follows:

      export const FILTER_OPTIONS: FilterOption[] = [
        { label: 'Original', value: 'original', filter: ORIGINAL_MATRIX },
        { label: 'Retro', value: 'retro', filter: RETRO_COLOR_MATRIX },
        { label: 'Invert', value: 'invert', filter: REVERSE_COLOR_MATRIX },
        { label: 'Enhance', value: 'enhance', filter: ENHANCE_COLOR_MATRIX },
        { label: 'Whiten', value: 'whitening', filter: WHITENING_COLOR_FILTER }
      ];
  3. Initialize the filter state.

    Initialize the filter state of each image in the component lifecycle.

    aboutToAppear(): void {
      this.imageFilterTags = new Array<string>(CAROUSEL_DATA_SOURCE.length).fill('original');
    }
  4. Apply a filter to an image.

    Use colorFilter to apply the filter effect to the image component. This step is the core implementation.

    Image(imgRes)
      .width('100%')
      .height('100%')
      .objectFit(ImageFit.Contain)
      .borderRadius(16)
      .colorFilter(this.getFilterByTag(this.imageFilterTags[index]))

    For carousel image display, different images are switched and each image needs to be set with a filter. Therefore, you need to obtain the filter object based on the filter tag recorded for each image. The key auxiliary method is as follows:

    private getFilterByTag(tag: string): ColorFilter | number[] {
      const option = FILTER_OPTIONS.find(opt => opt.value === tag);
      return option ? option.filter : ORIGINAL_MATRIX;
    }

FAQs

[h2]Why Does colorFilter Not Take Effect for SVG Images?

Symptom

colorFilter functions properly for PNG and JPG images, but does not take effect for SVG images.

Possible Cause

This is related to the API version and SVG internal structure.

Solution

If you want to change the color of an SVG image in an earlier version, you are advised to convert the SVG image to a PNG or PixelMap image and then apply colorFilter to it, or use the fillColor attribute. (This attribute is applicable to monochrome icons. The image source must contain the parameter configuration of the fill attribute, and the value of the fill attribute cannot be none.)

[h2]Why Does renderMode Not Take Effect After colorFilter Is Set?

Symptom

The renderMode: ImageRenderMode.Template attribute was originally set to color the icon black. However, the colorFilter attribute was used to add a filter, causing the template effect to disappear and the color to be displayed abnormally.

Possible Cause

The system specifications are not followed. According to the system specifications, when the colorFilter attribute is set, the renderMode attribute setting does not take effect.

Solution

Do not use colorFilter and renderMode attributes at the same time. If you need to color the image, use the colorFilter to simulate the template mode (that is, ignore the pixel color of the original image and retain only the alpha channel, and color the entire image with the target color). For example, to color the image red, the corresponding monochrome color matrix is as follows:

[
  0, 0, 0, 0, 1,
  0, 0, 0, 0, 0,
  0, 0, 0, 0, 0,
  0, 0, 0, 1, 0
]

Sample Code