Basic tutorial for Android -- 8.3.9 Paint API -- ColorFilter (color filter) (1-3)

Source: Internet
Author: User

Basic tutorial for Android -- 8.3.9 Paint API -- ColorFilter (color filter) (1-3)
This section introduces:

We have learned the MaskFilter (mask) and used its two sub-classes BlurMaskFilter to blur the effect. EmbossMaskFilter
This section describes how to use another API --ColorFilter(Color filter), same as MaskFilter,
Instead of directly using this class, we use three subclasses of this class:
Color matrix Color Filter: ColorMatrixColorFilter
Light Color Filter: LightingColorFilter
Filter of mixed color filterPorterducolorfilter
In this section, we will learn how to use the first ColorMatrixColorFilter. Open the ColorMatrixColorFilter document,

In general, a color matrix of 4x5 can be used to change the color, change the pixel saturation, and convert YUV to RGB!
The ColorMatrix In the constructor is the color matrix, which is also the core of our learning. Let me hear it one by one!
PS: ColorMatrix API documentation

1. Popularization of common sense: RGBA model:

RGBA doesn't know you 've heard of it. You know about the yellow, green, and blue. The three colors of light, and RAGB, on this basis, have an extra transparency!
R (Red),G (Green),B (Blue),A (Alpha transparency)In addition, it must be 3 of the pigment.
The primary colors are distinguished. The most obvious difference is that the three primary colors of the pigment Replace the green colors in the three primary colors of light with yellow! You just need to know,
If you are interested, you can use Baidu ~

Some terms: Tone/hue-- Color transmitted by objects
Saturation-- The purity of the color, from 0 (Gray) to 100% (saturated) to describe
Brightness/brightness-- Relative brightness of colors
2. Explanation of ColorMatrix

For example, color matrix (4*5), we can modify the values in the Matrix to achieve black/white photos, pornographic photos, high contrast and other effects!
The diagram of the hand-torn color matrix is as follows:

I don't know if you understand it. If you have learned a high number, you must be familiar with it. It's nothing more than a matrix's cross multiplication. It doesn't matter if you have never learned it.
The calculation method is in the lower right corner,Use each row of the color matrix * each column of the color matrix component!
A typical example is to compare the results before and after processing.Color values * a constantFor example, let the third line (blue)
Multiply by 2, and the effect becomes pan-blue. Of course, we must write code to verify the above results!

3. write code to verify the function of ColorMatrix

Here is an example of writing rotten street, an ImageView, 4*5 edittexts, a reset button, and a generate button,
Let's take a look:

The source image, yellow, green, red, high contrast, color phase conversion, and yellow retro

Next we will write the code to complete the above results:
Code Implementation:

First, layout filesActivity_main.xml:


  
      
       
        
    
     
    
   
      

NextMainActivity. java:

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private ImageView img_show; private GridLayout gp_matrix; private Button btn_reset; private Button btn_Change; private Bitmap mBitmap; private int mEtWidth, mEtHeight; private EditText [] mEts = new EditText [20]; private float [] mColorMatrix = new float [20]; private Context mContext; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mContext = MainActivity. this; bindViews (); gp_matrix.post (new Runnable () {@ Override public void run () {mEtWidth = gp_matrix.getWidth ()/5; mEtHeight = gp_matrix.getHeight ()/4; // Add 5*4 EditText for (int I = 0; I <20; I ++) {EditText editText = new EditText (mContext); mEts [I] = editText; gp_matrix.addView (editText, mEtWidth, mEtHeight) ;}initmatrix () ;}} private void bindViews () {img_show = (ImageView) findViewById (R. id. img_show); gp_matrix = (GridLayout) findViewById (R. id. gp_matrix); btn_reset = (Button) findViewById (R. id. btn_reset); btn_Change = (Button) findViewById (R. id. btn_Change); mBitmap = BitmapFactory. decodeResource (getResources (), R. mipmap. img_meizi); img_show.setImageBitmap (mBitmap); btn_reset.setOnClickListener (this); btn_Change.setOnClickListener (this);} // defines a method for initializing the color matrix private void initMatrix () {for (int I = 0; I <20; I ++) {if (I % 6 = 0) {mEts [I]. setText (String. valueOf (1);} else {mEts [I]. setText (String. valueOf (0) ;}}// defines a method to obtain the matrix value. private void getMatrix () {for (int I = 0; I <20; I ++) {mColorMatrix [I] = Float. valueOf (mEts [I]. getText (). toString () ;}}// process the image private void setImageMatrix () {Bitmap bmp = Bitmap based on the color matrix value. createBitmap (mBitmap. getWidth (), mBitmap. getHeight (), Bitmap. config. ARGB_8888); android. graphics. colorMatrix colorMatrix = new android. graphics. colorMatrix (); colorMatrix. set (mColorMatrix); Canvas canvas = new Canvas (bmp); Paint paint = new Paint (Paint. ANTI_ALIAS_FLAG); paint. setColorFilter (new ColorMatrixColorFilter (colorMatrix); canvas. drawBitmap (mBitmap, 0, 0, paint); img_show.setImageBitmap (bmp) ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_Change: getMatrix (); setImageMatrix (); break; case R. id. btn_reset: initMatrix (); getMatrix (); setImageMatrix (); break ;}}}

The code is very simple. Load the layout and add 5*4 edittexts to GridLayout.
The post () method ensures that the length and width of GridLayout are obtained only after being loaded. Otherwise, the GridLayout length is obtained.
The value cannot be obtained when it is wide! Then, we define three methods: initial matrix, get the matrix value, and
Matrix value to process images ~ Isn't it easy ~
But here you may have somethingQuestion:

"Can we only modify the color matrix in this way when processing images? It will be very troublesome for the next time. Who will remember the Matrix?
Should be filled in? Is there a simple way to process images? "
A: Yes. You can check the document and find several common methods:
SetRotate(Int axis, float degrees): Set the color.
SetSaturation(Float sat): sets the saturation.
SetScale(Float rScale, float gScale, float bScale, float aScale): sets the brightness.
Let's write an example to try these three methods!

4. Use ColorMatrix's three methods to process images

Run:

Code Implementation:

First, let's compile an image processing tool class. We pass in Bitmap, color phase, saturation and brightness, and then return
Processed image:ImageHelper. java:

/*** Created by Jay on 0028. */public class ImageHelper {/*** this method is used to process images and adjust the image ** @ param bm: The image to be processed ** @ param hue: tone * @ param saturation: saturation * @ param lum: brightness */public static Bitmap handleImageEffect (Bitmap bm, float hue, float saturation, float lum) {Bitmap bmp = Bitmap. createBitmap (bm. getWidth (), bm. getHeight (), Bitmap. config. ARGB_8888); Canvas canvas = new Canvas (bmp); Paint paint = new Paint (Paint. ANTI_ALIAS_FLAG); ColorMatrix hueMatrix = new ColorMatrix (); hueMatrix. setRotate (0, hue); // 0 indicates R, red hueMatrix. setRotate (1, hue); // 1 stands for G, green hueMatrix. setRotate (2, hue); // 2 stands for B, blue ColorMatrix saturationMatrix = new ColorMatrix (); saturationMatrix. setSaturation (saturation); ColorMatrix lumMatrix = new ColorMatrix (); lumMatrix. setScale (lum, 1); ColorMatrix imageMatrix = new ColorMatrix (); imageMatrix. postConcat (hueMatrix); imageMatrix. postConcat (saturationMatrix); imageMatrix. postConcat (lumMatrix); paint. setColorFilter (new ColorMatrixColorFilter (imageMatrix); canvas. drawBitmap (bm, 0, 0, paint); return bmp ;}}

Next, we will release the layout,Activity_main.xml:


  
      
       
        
         
       
        
         
         
        
       
      
     
    
   
  

Finally, ourMainActivity. java:

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener{    private ImageView img_meizi;    private SeekBar sb_hue;    private SeekBar sb_saturation;    private SeekBar sb_lum;    private final static int MAX_VALUE = 255;    private final static int MID_VALUE = 127;    private float mHue = 0.0f;    private float mStauration = 1.0f;    private float mLum = 1.0f;    private Bitmap mBitmap;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.img_meizi);        bindViews();    }    private void bindViews() {        img_meizi = (ImageView) findViewById(R.id.img_meizi);        sb_hue = (SeekBar) findViewById(R.id.sb_hue);        sb_saturation = (SeekBar) findViewById(R.id.sb_saturation);        sb_lum = (SeekBar) findViewById(R.id.sb_lum);        img_meizi.setImageBitmap(mBitmap);        sb_hue.setMax(MAX_VALUE);        sb_hue.setProgress(MID_VALUE);        sb_saturation.setMax(MAX_VALUE);        sb_saturation.setProgress(MID_VALUE);        sb_lum.setMax(MAX_VALUE);        sb_lum.setProgress(MID_VALUE);        sb_hue.setOnSeekBarChangeListener(this);        sb_saturation.setOnSeekBarChangeListener(this);        sb_lum.setOnSeekBarChangeListener(this);    }    @Override    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {        switch (seekBar.getId()) {            case R.id.sb_hue:                mHue = (progress - MID_VALUE) * 1.0F / MID_VALUE * 180;                break;            case R.id.sb_saturation:                mStauration = progress * 1.0F / MID_VALUE;                break;            case R.id.sb_lum:                mLum = progress * 1.0F / MID_VALUE;                break;        }        img_meizi.setImageBitmap(ImageHelper.handleImageEffect(mBitmap, mHue, mStauration, mLum));    }    @Override    public void onStartTrackingTouch(SeekBar seekBar) {}    @Override    public void onStopTrackingTouch(SeekBar seekBar) {}}

The Code is also very simple. I will not explain it here ~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.