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:
- BlurMaskFilter.Blur.NORMAL: Blur inside and outside
- BlurMaskFilter.Blur.OUTER: Blur outside
- BlurMaskFilter.Blur.INNER: Blur inside
- BlurMaskFilter.Blur.SOLID: Bold inside, blur outside
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:
Application: Add in the application node of the configuration file: android:hardwareAccelerated="true"
Activity: Add in the activity node of the configuration file android:hardwareAccelerated="false"
View: Can be called after obtaining the View object, or directly set in the View's onDraw() method: view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
Sample Code Download:
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.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-2.3.7 ProgressBar (Progress 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.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.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
-4.3.1 BroadcastReceiver Beginner
-4.3.2 BroadcastReceiver Advanced
-4.4.1 ContentProvider Introduction
-4.4.2 ContentProvider Advanced - Document Provider
-4.5.2 Passing Complex Data with Intent
- 5.1 Fragment Basic Overview
- 5.2.1 Fragment Example Deep Dive — Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Deep Dive — Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Deep Dive — Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Deep Dive — Bottom Navigation Bar + ViewPager for Swipe Page Switching
- 5.2.5 Fragment Example Deep Dive — Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access — File Storage and Read/Write
- 6.2 Data Storage and Access — SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access — Introduction to SQLite Database
- 6.3.2 Data Storage and Access — SQLite Database Revisited
- 7.1.1 Android Network Programming Essentials and HTTP Protocol Study
- 7.1.2 Android HTTP Request and Response Headers Study
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android WebService Call
- 7.5.1 WebView (Web View) Basic Usage
- 7.5.2 WebView and JavaScript Interaction Basics
- 7.5.3 WebView Considerations After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Webpage Error Code Information
- 7.6.1 Socket Network Basics Preparation
- 7.6.2 TCP Protocol Based Socket Communication (1)
- 7.6.3 TCP Protocol Based Socket Communication (2)
- 7.6.4 UDP Protocol Based Socket Communication
- 8.1.1 13 Drawable Types in Android Summary Part 1
- 8.1.2 13 Drawable Types in Android Summary Part 2
- 8.1.3 13 Drawable Types in Android Summary Part 3
- 8.2.1 Bitmap (Bitmap) Full Analysis Part 1
- 8.2.2 Bitmap OOM Issues
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Drawing Class Practical Examples
- 8.3.3 Paint API — MaskFilter (Mask)
- 8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API — Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API — ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API — ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API — ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API — PathEffect (Path Effect)
- 8.3.13 Paint API — Shader (Image Rendering)
- 8.3.14 Paint Enum/Constant Values and ShadowLayer Shadow Effects
- 8.3.15 Paint API — Typeface (Font Style)
- 8.3.16 Canvas API Detailed Explanation (Part 1)
- 8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
- 8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Android Animation Collection — Frame Animation
- 8.4.2 Android Animation Collection — Tween Animation
- 8.4.3 Android Animation Collection — Property Animation - Introduction
- 8.4.4 Android Animation Collection — Property Animation - Revisited
- 9.1 Using SoundPool to Play Sound Effects (Duang~)
- 9.2 MediaPlayer for Audio and Video Playback
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord for Audio Recording
- 10.1 TelephonyManager (Telephony Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Topic (1) — Introduction
- 10.11 Sensor Topic (2) — Orientation Sensor
- 10.12 Sensor Topic (3) — Accelerometer/Gyroscope Sensor
- 10.12 Sensor Topic (4) — Understanding Other Sensors
- 10.14 Android GPS Introduction -11.0 "2015 Latest Android Basic Beginner's Tutorial" Completed and Celebrated
-12.2 DrySister Viewing Girls App (Version 1) -- 2. Parsing Backend Data
-12.4 DrySister Viewing Girls App (Version 1) -- 4. Adding Data Caching (Introducing SQLite)