Easy Tutorial
❮ Mobile Testing Skills Git Graphical ❯

8.3.3 Paint API - MaskFilter (Mask)

Category Android Basic Tutorial

Introduction:

>

In the Android Basic Tutorial - 8.3.1 Detailed Explanation of Three Drawing Tool Classes, there is a method in the Paint class:

setMaskFilter(MaskFilter maskfilter): Sets the MaskFilter, which can achieve filter effects such as blurring and embossing by using different MaskFilters! We usually do not directly use MaskFilter but instead use its two subclasses:

BlurMaskFilter: Specifies a blur style and radius to process the edges of the Paint.

EmbossMaskFilter: Specifies the direction of the light source and the intensity of the ambient light to add an embossed effect. Let's write an example to test this out!

Official API Documentation: BlurMaskFilter; EmbossMaskFilter;


1. BlurMaskFilter (Blur Effect)

>

To see the filter and embossed effects in action, let's look at an example:

Code Example:

Run Effect Image:

Implementation Code:

>

Here, we create a custom View to handle the drawing!

BlurMaskFilterView.java:

/**
 * Created by Jay on 2015/10/21 0021.
 */
public class BlurMaskFilterView extends View {

    public BlurMaskFilterView(Context context) {
        super(context);
    }

    public BlurMaskFilterView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BlurMaskFilterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        BlurMaskFilter bmf = null;
        Paint paint = new Paint();
        paint.setAntiAlias(true);          // Anti-alias
        paint.setColor(Color.RED);         // Paint color
        paint.setStyle(Paint.Style.FILL);  // Paint style
        paint.setTextSize(68);             // Text size in px
        paint.setStrokeWidth(5);           // Stroke width

        bmf = new BlurMaskFilter(10f, BlurMaskFilter.Blur.NORMAL);
        paint.setMaskFilter(bmf);
        canvas.drawText("最喜欢看曹神日狗了~", 100, 100, paint);
        bmf = new BlurMaskFilter(10f, BlurMaskFilter.Blur.OUTER);
        paint.setMaskFilter(bmf);
        canvas.drawText("最喜欢看曹神日狗了~", 100, 200, paint);
        bmf = new BlurMaskFilter(10f, BlurMaskFilter.Blur.INNER);
        paint.setMaskFilter(bmf);
        canvas.drawText("最喜欢看曹神日狗了~", 100, 300, paint);
        bmf = new BlurMaskFilter(10f, BlurMaskFilter.Blur.SOLID);
        paint.setMaskFilter(bmf);
        canvas.drawText("最喜欢看曹神日狗了~", 100, 400, paint);

        setLayerType(View.LAYER_TYPE_SOFTWARE, null);     // Disable hardware acceleration
    }
}

>

From the above code example, we can see that we use BlurMaskFilter by instantiating it in the constructor:

BlurMaskFilter(10f, BlurMaskFilter.Blur.NORMAL);

We can control these two parameters:

First parameter: Specifies the radius of the blur edge;

Second parameter: Specifies the style of the blur, with options:

To make it clearer, let's try an image:

Here, we changed the blur radius to 50 for a more noticeable effect.


2. EmbossMaskFilter (Embossed Effect)

>

As the title suggests, by specifying the direction of the ambient light source and its intensity, an embossed effect is added. Let's see an example:

Code Example:

Run Effect Image:

Implementation Code:

/**
 * Created by Jay on 2015/10/22 0022.
 */
public class EmbossMaskFilterView extends View {

    public EmbossMaskFilterView(Context context) {
        super(context);
    }

    public EmbossMaskFilterView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EmbossMaskFilterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float[] direction = new float[]{1, 1, 3};   // Set light source direction
        float light = 0.4f;     // Set ambient light brightness
        float specular = 8;     // Define specular reflection coefficient
        float blur = 3.0f;      // Blur radius
        EmbossMaskFilter emboss = new EmbossMaskFilter(direction, light, specular, blur);

        Paint paint = new Paint();
        paint.setAntiAlias(true);          // Anti-alias
        paint.setColor(Color.BLUE);        // Paint color
        paint.setStyle(Paint.Style.FILL);  // Paint style
        paint.setTextSize(70);             // Text size in px
        paint.setStrokeWidth(8);           // Stroke width
        paint.setMaskFilter(emboss);

        paint.setMaskFilter(emboss);
        canvas.drawText("最喜欢看曹神日狗了~", 50, 100, paint);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_bg_meizi1);
        canvas.drawBitmap(bitmap, 150, 200, paint);

        setLayerType(View.LAYER_TYPE_SOFTWARE, null);     // Disable hardware acceleration
    }
}

>

From the effect image, we can see some of the EmbossMaskFilter effects. The text clearly shows the embossed lines, while the image of the girl is less obvious. The settings related to EmbossMaskFilter are also done in the constructor.

EmbossMaskFilter(float[] direction, float ambient, float specular, float blurRadius) parameters are:

direction: Float array to control the light source direction in x, y, z axes ambient: Set ambient light brightness, between 0 and 1 specular: Specular reflection coefficient blurRadius: Blur radius

You can modify these values to try different effects. For example, I changed the above values for another effect:

// Here, for clarity, I changed it to green


3. Notes

>

When using MaskFilter, note that when targetSdkVersion >= 14, MaskFilter will not work because Android versions above API 14 default to hardware acceleration, which takes advantage of the GPU's features to make drawing smoother but consumes more memory. Well, we can turn off hardware acceleration at different levels, usually by disabling it:


Sample Code Download:

MaskFilterDemo.zip


Summary:

>

This section demonstrates the Paint API, setMaskFilter(MaskFilter maskfilter), and introduces

the use of BlurMaskFilter and EmbossMaskFilter. Basic usage of MaskFilter subclasses: BlurMaskFilter (blur effect) and EmbossMaskFilter (embossing effect), which are quite simple. Learning more will not harm our advanced custom controls. That's all for now, thank you~

By the way, I forgot to mention that there is a class in the SDK examples demonstrating these two usages:

samples\android-xx\legacy\ApiDemos\src\com\example\android\apis\graphics directory下的:FingerPaint.java file~

-1.0 Android Basic Introduction Tutorial

-1.0.1 2015 Latest Android Basic Introduction Tutorial Table of Contents

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial for Basic Local Repository Operations

-1.5.2 Git: Setting Up Remote Repository with GitHub

-1.6 How to Use 9-Patch Images

-1.7 Interface Prototype Design

-1.8 Project Source Analysis (Various Files, Resource Access)

-1.9 Android Program Signing and Packaging

-1.11 Decompiling APK to Obtain Code & Resources

-2.1 Concepts of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 Detailed Explanation of TextView (Text Field)

-2.3.2 Detailed Explanation of EditText (Input Field)

-2.3.3 Button (Button) and ImageButton (Image Button)

-2.3.4 ImageView (Image View)

-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Drag Bar)

-2.3.9 RatingBar (Star Rating Bar)

-2.4.1 ScrollView (Scroll Bar)

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Basic Explanation of Adapter

-2.4.5 Simple Usage of ListView

-2.4.6 Optimization of BaseAdapter

-2.4.7 Focus Issues with ListView

-2.4.8 Solving Checkbox Misalignment Issue in ListView

-2.4.9 Data Update Issue with ListView

-2.5.0 Building a Reusable Custom BaseAdapter

-2.5.1 Implementation of Multi-Layout ListView Items

-2.5.2 Basic Usage of GridView (Grid View)

-2.5.3 Basic Usage of Spinner (List Option Box)

-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Field)

-2.5.5 Basic Usage of ExpandableListView (Collapsible List)

-2.5.6 Basic Usage of ViewFlipper (Flip View)

-2.5.7 Basic Usage of Toast

-2.5.8 Detailed Explanation of Notification (Status Bar Notification)

-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)

-2.6.0 Basic Usage of Other Common Dialogs

-2.6.1 Basic Usage of PopupWindow (Floating Box)

-2.6.2 Menu (Menu)

-2.6.3 Simple Usage of ViewPager

-2.6.4 Simple Usage of DrawerLayout (Official Side Sliding Menu)

-3.1.1 Event Handling Mechanism Based on Listeners

-3.2 Event Handling Mechanism Based on Callbacks

-3.3 Analysis of Handler Message Passing Mechanism

-3.4 TouchListener vs OnTouchEvent + Multi-Touch

-3.5 Listening to Content Changes in EditText

-3.6 Responding to System Setting Events (Configuration Class)

-3.7 AsyncTask Asynchronous Task

-3.8 Gestures (Gestures)

-4.1.1 Activity Beginner

-4.1.2 Activity Intermediate

-4.1.3 Activity Advanced

-4.2.1 Service Introduction

-4.2.2 Service Advanced

-4.2.3 Service Expert

-4.3.1 BroadcastReceiver Beginner

-4.3.2 BroadcastReceiver Advanced

-4.4.1 ContentProvider Introduction

-4.4.2 ContentProvider Advanced - Document Provider

-4.5.1 Basic Usage of Intent

-4.5.2 Passing Complex Data with Intent

-12.1 Android Practice: DrySister Viewing Girls App (Version 1) -- Project Setup and Simple Implementation

-12.2 DrySister Viewing Girls App (Version 1) -- 2. Parsing Backend Data

-12.3 DrySister Viewing Girls App (Version 1) -- 3. Image Loading Optimization (Writing a Small Image Caching Framework)

-12.4 DrySister Viewing Girls App (Version 1) -- 4. Adding Data Caching (Introducing SQLite)

-12.5 DrySister Viewing Girls App (Version 1) -- 5. Code Review, Adjustment, and Logging Class Writing

-12.6 DrySister Viewing Girls App (Version 1) -- 6. Icon Creation, Obfuscation, Signing and Packaging, APK Slimming, App Release

WeChat Follow

❮ Mobile Testing Skills Git Graphical ❯