当前位置:网站首页>A list of common methods for customizing paint and canvas of view
A list of common methods for customizing paint and canvas of view
2022-06-26 09:58:00 【Bai Ze】
Article structure
- Customize View And Paint and Canvas List of common methods
- Paint Quick look-up table for common operation
- `Canvas` A quick look-up table is a common method
- `Paint` paint brush ️
- `Canvas` canvas
Customize View And Paint and Canvas List of common methods
Recently, when customizing controls , I found many ways to remember , If you don't write often, you will forget . I had no choice but to review the great God article once :GcsSloop and HenCoder, And sort out your notes just in case .
Paint Quick look-up table for common operation
| Operation type | relevant api | remarks |
|---|---|---|
| Anti-Aliasing | setAntiAlias (boolean aa) constructor (Paint.ANTI_ALIAS_FLAG) | Turn on anti aliasing ,Paint Constructors enable anti aliasing |
| Fill the style | setStyle (Style style) | Fill the style :FILL,STROKE,FILL_AND_STROKE |
| Line shape | setStrokeWidth (float width) setStrokeCap (Cap cap) setStrokeJoin (Join join) setStrokeMiter (float miter) | Set line width , Set thread head shape , Set corner shape , Set up MITER Maximum value of type-A corner extension line |
| initialization | reset () set (Paint src) setFlage (int flags) | Reset Paint attribute , Copy Paint All attributes , Batch settings flags. |
| Set coloring | setColor (int color) setARGB (int a,int r,int g,int b) setShader (Shader shader) setColorFilter (ColorFilter colorFilter) setXfermode (Xfermode xfermode) | Set the color Set up shaders (Shader) Set up color filtering Set color scheme |
| Color optimization | setDither (boolean dither) setFilterBitmap (boolean filter) | Set dithering to optimize the rendering effect when the color depth is reduced , Set up bilinear filtering to optimize Bitmap Zoom in on the paint |
| Graphic outline | setPathEffect (PathEffect effect) | Set the effect for the outline of the drawing : Single effect :CornerPathEffect,DiscretePathEffect,DashPathEffect,PathDashPatheffect Combined effect :SumPathEffect,ComposePathEffecct |
| Draw additional effects | setShadowLayer(float radius,float dx,float dy,int shadowColor) setMaskFilter (MaskFilter maskfilter) | setShadowLayer Add a layer of shadow under the painting content later .setMaskFilter Set the additional effect above the paint layer .MaskFilter There are two kinds of :BlurMaskFilter( Fuzzy ) and EmbossMaskFilter( Relief ) |
| Words are related | drawText () | Paint More than half of the methods are drawText() dependent |
| Get the drawn Path | getFillPath (Path src,Path dst) getTextPath (String text, int start, int end, float x, float y, Path path) getTextPath (char[] text, int index, int count, float x, float y, Path path) | according to paint Set up , Calculate the plot Path Or the actual words Path. |
Canvas A quick look-up table is a common method
| Operation type | relevant api | remarks |
|---|---|---|
| Draw colors | drawColor (int color) drawColor (int color, PorterDuff.Mode mode) drawRGB (int r,int g,int b) drawARGB (int a,int r,int g,int b) | Fill the canvas with a single color |
| Draw shape | spot :drawPoint (float x,float y,Paint paint) drawPoints (float[] pts,Paint paint) drawPoints (float[] pts,int offset,int count,Paint paint) offset: Skip the first few numbers of the array ,count: The number of points Line :drawLine (float startX,float startY,float stopX,float stopY,Paint paint) drawLines (float[] pts,Paint paint) drawLines (float[] pts,int offset,int count,Paint paint) rectangular :drawRect (Rect rect,Paint paint) drawRect (RectF rect,Paint paint) drawRect (float left,float top,float right,float bottom,Paint paint) Rounded rectangle :drawRoundRect (RectF rect,float ex,float ry,Paint paint) drawRoundRect (float left, float top, float right, float bottom, float rx, float ry,Paint paint) The ellipse :drawOval (RectF oval,Paint paint) drawOval (float left,float top,float right,float bottom,Paint paint) round :drawCircle (float cx, float cy, float radius,Paint paint) arc :drawArc (RectF oval,float startAngle,float sweepAngle,boolean useCenter,Paint paint) drawArc (float left, float top, float right, float bottom, float startAngle, float sweepAngle, boolean useCenter,Paint paint) | Draw basic figures |
| Drawing pictures | drawBitmap (Bitmap bitmap,float left,float top,Paint paint) drawBitmap (Bitmap bitmap,Rect src,RectF dst,Paint paint) drawBitmap (Bitmap bitmap,Rect src,Rect dst,Paint paint) drawBitmap (Bitmap bitmap, Matrix matrix,Paint paint) drawPicture (Picture picture) drawPicture (Picture picture,RectF dst) drawPicture (Picture picture,Rect dst) | Draw bitmaps and pictures |
| Draw text | drawText (char[] text,int index,int count,float x,float y,Paint paint)drawText (String text,float x,floaty,Paint paint)drawText (String text,int star,int end,float x,float y,Paint paint) drawText (CharSequence text,int start,int end,float x,float y,Paint paint) drawTextOnPath (char[] text,int index,int count,Path path,float hOffset,float vOffset,Paint paint) drawTextOnPath (String text,Path path,float hOffset,float vOffset,Paint paint) | Draw text , Draw text according to the path , When drawing text, specify the position of each text ( Have been abandoned ) |
| Draw the path | drawPath (Path path,Paint paint) | Draw the path , This function is also needed when drawing Bezier curves |
| Vertex operation | drawVertices (VertexMode mode,int vertexCount,float[] verts,int vertOffset,float[] texs, int texOffset,int[] colors,int colorOffset,short[] indices, int indexOffset, int indexCount,Paint paint) drawBitmapMesh (Bitmap bitmap,int meshWidth,int meshHeight,float[] verts,int vertOffset,Paint paint) | You can deform the image by manipulating vertices , drawVertices Act directly on the canvas ,drawBitmapMesh Works only on drawn Bitmap |
| Canvas clipping | clipPath (Path path) clipRect (Rect rect) clipRect (RectF rect) clipRect (int left, int top, int right, int bottom) clipRect (float left, float top, float right, float bottom) | Set the display area of the canvas |
| Canvas snapshot | save () restore () saveLayerXXX () restoreToCount (int saveCount) getSaveCount () | Save current state , Will scroll to the last saved state , Save layer state , Will scroll to the specified state , Get save times |
| Canvas transform | translate (float dx, float dy) scale (float sx, float sy) scale (float sx, float sy, float px, float py) rotate (float degrees) rotate (float degrees, float px, float py) skew (float sx, float sy) | Displacement 、 The zoom 、 rotate 、 Crosscutting |
| Matrix( matrix ) | getMatrix () setMatrix (Matrix matrix) concat (Matrix matrix) | In fact, the displacement of the canvas , Scaling and other operations are image matrix Matrix, It's just Matrix Difficult to understand and use , Therefore, some common methods are encapsulated |
Paint paint brush ️
Line shape
Set thread head shape : setStrokeCap()
Cap For enumeration type , Namely :BUFF Flat head ,ROUND Round head ,SQUARE Fangtou , The default is BUFF.

Set corner shape : setStrokeJoin()
Join For enumeration type , There are three values to choose from :MITER Sharp corners ,BEVEL flat horn ,ROUND Round corners , The default is MITER.

Set the maximum value of the sharp corner supplementary extension line : setStrokeMiter()
Is for setStrokeJoin() Method supplement .MITER Type join points have an additional rule : When the sharp corner is too long , Automatically use BEVEL To render connection points . As for how sharp is a sharp angle , from setStrokeMiter() Of miter Parameter determination .

The ratio of the distance between the outer edge of the sharp corner and the inner corner to the width of the line .
setShader() :Shader
Shader It mainly uses several subclasses :LinearGradient,RadialGradient,SweepGradient,BitmapShader,ComposeShader
setColorFilter() :ColorFilter
ColorFilter Don't use , It uses its three subclasses :LightingColorFilter,PorterDuffColorFilter,ColorMatrixColorFilter
setXfermode() :Xfermode
Color optimization
Set the jitter of the image : setDither()
In the real world , Dithering is more useful when the image is rendered with reduced color depth , Avoid large color bands and color patches .

Whether to use bilinear filtering to draw Bitmap : setFilterBitmap()
Android By default, the nearest neighbor interpolation algorithm is used to draw the enlarged image , It's a simple algorithm , But there will be mosaic effect .setFilterBitmao() You can make the image when you zoom in , Appears smoother .

Set the effect for the outline of the drawing :setPathEffect(PathEffect effect)
PathEffect Set the effect for the drawing outline , Yes Canvas All figures are valid .Android
There is 6 Kind of PathEffect, There are two kinds of ,
- Single effect :
CornerPathEffectDiscretePathEffectDashPathEffectPathDashPathEffect - Combined effect :
SumPathEffectComposePathEffect
1. Single effect :CornerPathEffect
Round all the corners .
Construction method :CornerPathEffect ( float radius ) raduis: radius .
PathEffect pathEffect = new CornerPathEffect(20);
paint.setPathEffect(pathEffect);
...
canvas.drawPath(path,paint);
effect :
2. Single effect :DiscretePathEffect
Random deviation of lines ( discrete ), The degree of deviation is determined by the parameters .
Construction method :DiscretePathEffect ( float segmentLength,float deviation ) segmentLength: Used to splice the length of each segment .deviation: Deviation .
PathEffect pathEffect = new DiscretePathEffect(20,5);
...
effect :
3. Single effect :DashPathEffect
Draw lines with dashed lines .
Construction method :DashPathEffect ( float intervals[], float phase ) intervals[]: Specify the format of the dashed line , Element must be even ( least 2 individual ), according to 「 Draw line length , Blank length , Draw line length , Blank length …」 Draw in sequence . phase: The offset of the dotted line .
PathEffect pathEffect = new DashPathEffect(new float[]{20,10,5,10},0);
...
effect :
4. Single effect :PathDashPathEffect
Use one Path To draw 「 Dotted line 」.
Construction method :PathDashPathEffect(Path shape, float advance, float phase, Style style) shape: Draw the Path.advice: Two adjacent shape Distance between .phase: Offset of dashed lines .style: Specify the corner shape The transformation of .
style There are three enumeration values :
- TRANSLATE: Displacement
- ROTATE: rotate
- MORPH: variant

Path dashPath = ...;
PathEffect pathEffect = new PathDashPathEffect(dashPath,40,0,PathDashPathEffectStyle.TRANSLATE);
...
effect :
5. Mixed effect :SumPathEffect
According to two PathEffect Draw the targets separately .
Construction method :SumPathEffect ( PathEffect first, PathEffect second )
PathEffect dashEffect = new DashPathEffect(new float[]{20, 10}, 0);
PathEffect discreteEffect = new DiscretePathEffect(20, 5);
pathEffect = new SumPathEffect(dashEffect, discreteEffect);...
effect :
6. Mixed effect :ComposePathEffect
Start with the goal Path Use one PathEffect, And then to this changed Path Use another PathEffect.
Construction method :ComposePathEffect ( PathEffect outerpe, PathEffect innerpe )
PathEffect dashEffect = new DashPathEffect(new float[]{20, 10}, 0);
PathEffect discreteEffect = new DiscretePathEffect(20, 5);
pathEffect = new ComposePathEffect(dashEffect, discreteEffect);
effect :
Be careful : PathEffect In some cases, hardware acceleration is not supported , Hardware acceleration needs to be turned off for normal use :
- Canvas.drawLine() and Canvas.drawLines() Method when drawing a straight line ,setPathEffect() Hardware acceleration is not supported ;
- PathDashPathEffect Support for hardware acceleration is also problematic , So when used PathDashPathEffect When , Better turn off the hardware acceleration .
Canvas canvas
canvas It can be called canvas , It's the Android platform 2D The basis of graphic drawing , You can draw all kinds of things on it .
Rounded rectangle :drawRoundkRect()
There are two overloaded methods for drawing rounded rectangles :
// The first one is
RectF rectF = new RectF(100,100,800,400);
canvas.drawRoundRect(rectF,30,30,mPaint);
// The second kind API21 When you're at the end of the day (AndroidX There seems to be no such restriction )
canvas.drawRoundRect(100,100,800,400,30,30,mPaint);
Compared with rectangle , The rounded rectangle has two more parameters rx and ry, Represent the two radii of the ellipse respectively .

When rx Greater than half the width of the rectangle ,ry More than half the height of the rectangle , It becomes an ellipse .
边栏推荐
- druid数据源实现后台监控
- Force buckle ----- remove the maximum and minimum values from the array
- Jupyter Notebook遇到的问题
- SQL高级教程
- 从tf 1.x到tf 2.6(遇到的就过来更新更新)
- 【二分查找】4. 寻找两个正序数组的中位数
- My creation anniversary
- Common SQL add / delete / modify query statements
- 自动化测试——pytest本身及第三方模块介绍及使用
- install realsense2: The following packages have unmet dependencies: libgtk-3-dev
猜你喜欢

Cloud native essay using Hana expression database service on Google kubernetes cluster

thymeleaf中抽取公共片段

Software testing - how to select the appropriate orthogonal table

jar版本冲突问题解决
![[trajectory planning] testing of ruckig Library](/img/c7/51c0f6dc3bf7c7fa4528118a4c32fa.png)
[trajectory planning] testing of ruckig Library

Redis notes (15) - Pipeline (the client packages and sends batch commands to save network overhead)

Redis 新手入门

#云原生征文# 在 Google Kubernetes Cluster 上使用 HANA Expression Database Service

Specific implementation comparison between different programming languages

Upgrade idea to 2021.2 shortcut keys
随机推荐
Halcon photometric stereoscopic
Automated testing -- on the coexistence of Unitest and pytest initialization
Code statistics tools cloc and SCC
Openxcap usage
【二分查找】4. 寻找两个正序数组的中位数
LeetCode 剑指 Offer II 091.粉刷房子 - 原地修改
Crawler related articles collection: pyppeter, burpsuite
Retrofit common request methods and comments, post, get heard file upload
cento7.7安装ELK简单记录
libmagic 介绍
mysql学习总结
动态库连接 - 符号冲突 - 全局符号介入
Speed test of adding, deleting, modifying and querying 5million pieces of data in a single MySQL table
Glide's most common instructions
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ER
echo $?
力扣------从数组中移除最大值和最小值
install opencv-contrib-dev to use aruco code
install realsense2: The following packages have unmet dependencies: libgtk-3-dev
c语言语法基础之——局部变量及存储类别、全局变量及存储类别、宏定义 学习