8.3.17 Detailed Explanation of Canvas API (Part 2): Clipping Methods Collection
Category Android Basic Tutorial
Introduction:
>
This section continues with the detailed explanation of the Android drawing series, focusing on the Canvas API (Part 2). Today, we will explore the ClipXxx methods family in Canvas! We can see from the documentation that there are three types of Clip methods provided: clipPath(), clipRect(), and clipRegion();
By combining Path, Rect, and Region differently, you can almost support any shape of the clipping region!
Path: Can be open or closed curves, lines forming complex geometric shapes.
Rect: Rectangular area.
Region: Can be understood as a combination of areas, such as adding, subtracting, intersecting, or exclusive regions!
Region.Op defines the types of region operations supported by Region! We will discuss this later. Additionally, it's worth noting that the clipping we usually understand might be about clipping an already existing graphic, but in Android, clipping on Canvas must be done before drawing. If you clip the Canvas after drawing, it will not affect the already drawn graphics. Remember, Clip is for the Canvas, not the graphics! Alright, let's get straight to the content of this section!
Official API Documentation: Canvas
1. Detailed Explanation of Region.Op Combination Methods
>
The difficulty here is simply understanding this. Region represents an area, indicating a certain closed area on the Canvas layer! Of course, you can take your time to delve into this class, but what we usually focus on is just one of its enumeration values: Op.
3. Detailed Explanation of clipRect Method:
clipRect provides seven overloaded methods:
Parameters Introduction:
rect: Rect object, used to define the clipping area. Rect and RectF are similar in functionality but differ in precision and provided methods.
left: Left position of the rectangular clipping area.
top: Top position of the rectangular clipping area.
right: Right position of the rectangular clipping area.
bottom: Bottom position of the rectangular clipping area.
op: Combination mode of the clipping area.
The above four values can be either floating-point or integer types.
Usage Example:
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLACK);
mPaint.setTextSize(60);
canvas.translate(300, 300);
canvas.clipRect(100, 100, 300, 300); // Set display range
canvas.drawColor(Color.WHITE); // White background
canvas.drawText("Double 11, keep eating my dog food...", 150, 300, mPaint); // Draw string
Result:
From the example above, have you noticed? clipRect is affected by Canvas transformations. The white area is the unpainted area, so clipRect clips the canvas, and our drawing is performed on this clipped canvas! Anything outside this area will not be displayed!
4. Detailed Explanation of clipPath Method:
Compared to clipRect, clipPath only has two overloaded methods, and the usage is very simple. Just draw a Path and pass it in!
Usage Example:
Here, we reuse the example of the circular ImageView we wrote before in ImageView.
Implementation Code:
Custom ImageView: RoundImageView.java
/**
* Created by coder-pig on 2015/7/18 0018.
*/
public class RoundImageView extends ImageView {
private Bitmap mBitmap;
private Rect mRect = new Rect();
private PaintFlagsDrawFilter pdf = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG);
private Paint mPaint = new Paint();
private Path mPath = new Path();
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
// Pass in a Bitmap object
public void setBitmap(Bitmap bitmap) {
this.mBitmap = bitmap;
}
private void init() {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true); // Anti-aliasing
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap == null) {
return;
}
mRect.set(0, 0, getWidth(), getHeight());
canvas.save();
canvas.setDrawFilter(pdf);
mPath.addCircle(getWidth() / 2, getWidth() / 2, getHeight() / 2, Path.Direction.CCW);
canvas.clipPath(mPath, Region.Op.REPLACE);
canvas.drawBitmap(mBitmap, null, mRect, mPaint);
canvas.restore();
}
}
Layout Code: activity_main.xml:
<com.jay.demo.imageviewdemo.RoundImageView
android:id="@+id/img_round"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="5px"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private RoundImageView img_round;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_round = (RoundImageView) findViewById(R.id.img_round);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.meinv);
img_round.setBitmap(bitmap);
}
}
Result:
Additionally, the rounded ImageView created using this method will have noticeable aliasing, even if you set anti-aliasing for Paint and Canvas. If you require high quality, you can use Xfermode-PorterDuff to set image blending, which has almost no aliasing. See: Android Basic Tutorial - 8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
5. Download Sample Code:
Summary:
This section explains the three clipping methods in Canvas: clipPath(), clipRect(), and clipRegion(). The difficulty should be with the last one, with six different Op combination modes, which is not difficult, just a matter of understanding sets. clipPath() and clipRect() have no particular difficulties. Oh, today is Double 11, don't know if you've shopped till you dropped~
-1.0.1 2015 Latest Android Basic Tutorial Table of Contents
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android Apps with Eclipse + ADT + SDK
-1.2.2 Developing Android Apps 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 a Remote Repository on GitHub
-1.6 How to Play with 9-Patch Images
-1.7 Interface Prototype Design
-1.8 Project Source Analysis (Various Files, Resource Access)
-1.9 Signing and Packaging Android Applications
-1.11 Decompiling APK to Retrieve 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 Box)
-2.3.2 Detailed Explanation of EditText (Input Box)
-2.3.5. RadioButton (Radio Button) & Checkbox (Checkbox) -2.3.6 ToggleButton and 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.5 Simple Usage of ListView
-2.4.6 BaseAdapter Optimization
-2.4.8 Solving Checkbox Misalignment in ListView
-2.4.9 Data Update Issues in ListView
-2.5.0 Building a Reusable Custom BaseAdapter
-2.5.1 Implementing Multiple Item Layouts in ListView
-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 Box)
-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 Several 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 for 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 Deep Dive - Document Provider
-4.5.2 Passing Complex Data with Intent
-5.2.1 Fragment Example - Bottom Navigation Bar Implementation (Method 1)
-5.2.2 Fragment Example - Bottom Navigation Bar Implementation (Method 2)
-5.2.3 Fragment Example - Bottom Navigation Bar Implementation (Method 3)
-5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager Page Sliding
-5.2.5 Fragment Example - Simple Implementation of News (Shopping) App List Fragment
-6.1 Data Storage and Access - File Storage and Reading
-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 - Deep Dive into SQLite Database
-7.1.1 Android Network Programming and Learning HTTP Protocol
-7.1.2 Learning Android HTTP Request and Response Headers
-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.2 Android File Download (1)
-7.3.3 Android File Download (2)
-7.4 Android Calling WebService
-7.5.1 Basic Usage of WebView (Web View)
-7.5.2 Basic Interaction Between WebView and JavaScript
-7.5.3 Considerations for WebView in Android 4.4 and Later
-7.5.6 WebView Handling Error Codes from Web Pages
-7.6.1 Socket Learning Network Basics Preparation
-7.6.2 Socket Communication Based on TCP Protocol (1)
-7.6.3 Socket Communication Based on TCP Protocol (2)
-7.6.4 Socket Communication Based on UDP Protocol
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Bitmap (Bitmap) Comprehensive Analysis Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Practical Examples of Drawing Classes
- 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 Enumerations/Constants and ShadowLayer Shadow Effect
- 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 Frame Animation Collection in Android
- 8.4.2 Tween Animation Collection in Android
- 8.4.3 Property Animation in Android - First Encounter
- 8.4.4 Property Animation in Android - Another Encounter
- 9.1 Playing Sound Effects with SoundPool (Duang~)
- 9.2 MediaPlayer for Audio and Video Playback
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord to Record Audio
- 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 Topics (1) —— Introduction
- 10.11 Sensor Topics (2) —— Orientation Sensor
- 10.12 Sensor Topics (3) —— Accelerometer/Gyroscope Sensor
- 10.12 Sensor Topics (4) —— Understanding Other Sensors
- 10.14 Android GPS Introduction
- 11.0《2015 Latest Android Basic Beginner's Tutorial》Completion Celebration~
- 12.1 Android Practice: DrySister Viewing Girls App (First Edition) —— Project Setup and Simple Implementation
- 12.2 DrySister Viewing Girls App (First Edition) —— 2. Parsing Backend Data
- 12.3 DrySister Viewing Girls App (First Edition) —— 3. Image Loading Optimization (Writing a Small Image Cache Framework)
- 12.4 DrySister Viewing Girls App (First Edition) —— 4. Adding Data Caching (Introducing SQLite)
- 12.5 DrySister Viewing Girls App (First Edition) —— 5. Code Review, Adjustment, and Logging Class Writing
- 12.6 DrySister Viewing Girls App (First Edition) —— 6. Icon Creation, Obfuscation, Signing, APK Slimming, App Release