Learn All Android Canvas Draw Functions
IfЕсли youвы wouldхотите likeсоздать to create customсвой view fromс groundнуля up inв Android, it’sто helpfulвам toбдует knowполезано whichзнать drawфункции functionsдоступные areв availablecanvas.
onВ Canvas.этом Inблоге, thisя blog,перечислю Iвсе listдосупные everyдля drawрисования functionфункции available inв Android Canvas: 23 of them. Do go through them. You might find some you never knew existed (I myself was surprised by some)шутки. Below,Вы Iузнаете categorizeто themчто as:раньше Geometricalне Drawingзнали(Я Textбыл Drawingудивлен Colorих Drawingналичием)
ImageНиже Drawingя Inих caseразделилп youпо don’tкатегориям:
- Геометрический
makingрисование - Текстовое
views,рисование - Цветное
canрисование - Рисование
toизtheкартинки.
На случай если у вас нет опыта создания своего view, вы можете ссылаться на мануал под названием:
- Building Custom Component with Kotlin
Assuming-youПредположимwantвыtoхотитеbuildсоздатьaстраницуpageкотораяthatсостоитconsistизofповторяющихсяsomeобщихrepetitiveview.commonИviews.вамYouвозможноmightнеnotзахочетсяwantихtoповторять. - Custom Touchable Animated View in Kotlin
If-youЕслиwantedвыtoхотитеdrawнарисоватьyourсвоюownсобственную view,andиhavingтакsomeжеanimatedрисоватьdrawing,анимацию,нуandиinконечноKotlin…наhopeкотлине...thisЭтоwouldдолжноhelp. medium.comпомочь.Android: draw a custom view
Introduction
Геометрицеское Geometricalрисование
Множество Mostлюдей people useиспользует Canvas toдля drawрисования geometricalгеометрических items.объектов.
- drawLine
SimplyПросто
drawрисуетoneлиниюline.canvas.drawLine(startX, startY, endX, endY, paint)
Imagefor2.
postdrawLines
Если мы рисуем больше чем одну линию, взамен вызова
drawLine
много раз, мы можем использоватьdrawLines
.IfНамweнужноwantпредоставитьtoплоскийdrawмассивmoreзначенийthanкоординатaкакline,показаноinsteadниже.of performing drawLine multiple times, we could use drawLines. We just need to provide a flat float array list of the coordinate values as below.canvas.drawLines( floatArrayOf( startFirstX, startFirstY, endFirstX, endFirstY, startSecondX, startSecondY, endSecondX, endSecondY), paint)
Imagefor postdrawPoint While you could draw a point by drawing a line with the same start and end coordinates, this is considered a hack. So a3. drawPoint
functionПока
isвыprovided.можете нарисовать точку с помощью линии с тем же началом и концом координат, то это можно считать хаком. ПоэтомуdrawPoint
функция существует.canvas.drawPoint(coordinateX, coordinateY, paint)
-
4. drawPoints
AsКак
withвlines,случаеyouсcanлиниями,drawвыmultipleможетеpointsнарисоватьwithмножествоaточекflatсfloatпомощьюcoordinateмассиваarray.координат.canvas.drawPoints( floatArrayOf( startX, startY, startSecondX, startSecondY), paint)
-
5. drawRect
DrawРисование
aуглаrectangleиспользяusingкоординатыcoordinatesилиorклассaRect
.Rect class.canvas.drawRect( Rect(startX, topY, endX, bottomY), paint)
Imagefor6.
postdrawRoundRect
drawRoundRectЕсли
Ifвыyouхотитеwantуголaсrectangleкруглымиwithуглалми,roundedиспользуйтеcorners,drawRoundedRect
.useЭтоdrawRoundedRect.похожеIt’sнаsimilardrawRect
toноdrawRectсbutдополнительнымиwithradiusX
theиadditionradiusY
,ofдляradiusXопределенияandкривизныradiusYкруглогоtoугла.define the curvature of the rounded corners.canvas.drawRoundRect(rect, radiusX, radiusY, projectResources.paint)
ItdrawsФункция
anрисуетevenlyравномерноroundedкруглыйcornerугол,ifеслиradiusX
equalsиradiusY.radiusY
Imageравны.for post When radiusX = radiusY, it will have the usual rounded corners as below: Image for post If radiusX is bigger than radiusY, it will end up similar to below: Image for post If radiusX is smaller than radiusY, it will end up like this: Image for postdrawCircle7. drawCircle
isdrawCircle
simple.простой.ItЕмуonlyтребуютсяrequiresтолькоtheцентрcenterкоординатcoordinateиandрадиус.the radius.canvas.drawCircle( centerCoordinateX, centerCoordinateY, radius, paint)
Imagefor8.
postdrawOval
drawOvalВ
Unlikeотличииdrawingотaрисованияcircle,круга,weмыdon’tнеprovideпредоставляемaрадиус.radius.ВместоInstead,этогоweмыprovideуказываемaпрямоугольник,rect,иandовалtheбудетovalнарисованwillсоотвественно.be drawn accordingly.canvas.drawOval(rect, paint)
Imagefor9.
postdrawArc
drawArcРисование
Drawingдугиanиспользуетarcтоusesчтоtheиsameовал:mechanismклассasRect
.drawingИanимеетoval:дополнительныеusingпараметры,aтоRect.естьItstartAngle
,hassweepAngle
additionalиparameters,useCenter
.i.e. startAngle, sweepAngle, and useCenter.canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint)
FortheДля
startAngle,startAngle
,countпочитаемtheсерединуmiddleконцаendиofпрямоугольникtheкакrectначало,asтоthe start, i.e.есть 90°clockwise.поворотFromпоthere,часовойthe startAngle is considered 0°стрелке.TheОтсюда начальный угол считается нулём.sweepAngle
isрасчитываетсяthenотcalculatedstartAngle
.fromОбаstartAngle.используютBothзначенияuseградусовtheугла.angleuseCenter
degreeэто°булеваvalue.переменнаяuseCenterдляisопределенияaсвязанаbooleanаркаvariableсtoцентром.determine if the arc is connected to the center. The illustrations below depict the difference between useCenter as false and true. Image for post useCenter = false Image for post useCenter = truedrawPath Sometimes, we want to draw something that’s not restricted to normal geometrical lines. We use10. drawPath
here,Иногда
whereмы хотим нарисовать то что не отображается обычной геометрической фигурной линией. В этом случае мы пользуемdrawPath
, гдеPath
isэтоanобъектobjectкоторыйthatсостоитcontainsизtheпутиpathsкоторыйweмыwantхотимtoнарисовать.draw.ОнItсостоитconsistsизofфункцийfunctionsтакихsuchкакasmoveTo
moveToиandlineTo
,lineTo,какlikeкарандашaрисуетpencilиdrawingдвигается.andНижеmoving.примерBelowгдеisмыanдлелаемexampleкрестикwhereсweпомощьюdrawPath
.of a cross mark.val path = Path() path.moveTo(startX, topY) path.lineTo(endX, bottomY) path.moveTo(startX, bottomY) path.lineTo(endX, topY) canvas.drawPath(path, paint)
ImagefordrawPath
postоченьdrawPathполезнаяisфункция.aМногоveryктоusefulиспользуетfunction.еёManyдляuseсозданияitнарисованныхtoприложений.make11.
drawingdrawVerticesappЭто
programsотносительноinсложнаяAndroid.функция,Examplesкотораяbelow:рисуетAтреугольникиguideилиtoвершиныdrawingсinмаленькимиandroidточками.IntroductionДляandroid.jlelse.euпримера,Learnсto6createкоординатами,aможноPaintнарисоватьApplication4forтреугольника.AndroidПриPaintповторении,applicationsможноareиспользоватьbecomeдляfamousсложногоthanks3дtoмоделирования.MicrosoftКартинкаPaint,нижеwellэтоknown3dasроза,simplyнарисованнаяPaintсorпомощьюPaintbrush.drawVertices
.ItВотwasдетальноеa…объяснениеmedium.comего drawVertices This is a relatively complex function, which draws triangles or vertices with the minimal points. For example, with six coordinates, one can draw four triangles: Image for post When repeated, it can be used for complex 3D modeling. The art below (a 3D rose) is drawn with drawVertices. Image for postфункций. Here is a detailed explanation of its function.Text Drawing
IfЕсли
weнамhadнужноtoнарисоватьdrawтекстtextсамостоятельно,ourselves,этоthatбудетwouldдовольноbeлегко.super-tricky.БлагодаряThankfully,тому,weчтоhaveмыseveralимеемniceнесколькоoptions:прекрасный drawTextфункций.On Android, we normally use TextView for all our text. However, if we’d like better control of the text, such as dynamic changes, exact positioning, etc, the canvas12. drawText
comesНа
inандроиде,handy.мыTheобычноfunctionиспозуемfollows,TextView
withдляtext,всехcoordinate,нашихandтекстов.paint:Однако, если мы хотели бы лучший контроль текста, такие как динамическое изменения, точное положение. и т.п., то нам поможетdrawText
. Функция принимаетtext
,coordinateX
,coordinateY
иpaint
:canvas.drawText(text, coordinateX, coordinateY, paintText)
TheseareДовольна
funинтереснаяtoфункцияplayчтобыwithпоигратьсяifсsetней.correctly,13.
as shown below: Image for post You can find more detail here.- Draw StaticLayout
У
drawText
doesестьhaveограничения.limitations.ОнItнеdoesn’tпереноситwrapсловаtheнаlongerвторуюwordстроку.toТакtheжеsecondнеline.обрабатываетIt\n
alsoзнак.doesn’tПоэтомуhandleнамtheнужен/nStaticLayout
carryчтобыreturn.нарисоватьForтекстthat,которыйweможетneedпереноситьaдлинные слова на вторую линию.StaticLayout
toнеdrawсовсемtextфункцияthatрисованияcan wrap a long word to the second line. StaticLayout is not really a draw function of theна canvas,butноinsteadвзаменdrawsврисовываетitselfсебяinto theв canvas.BelowНижеisпримерhowотрисовки:it is drawn:val staticLayout = StaticLayout.Builder.obtain( TEXT, 0, TEXT.length, textPaint, width ).build()
1.
canvas.save()
canvas.translate(coordinateX, coordinateY)
staticLayout.draw(canvas)
canvas.restore()
The
result:
Image for post
14. drawPosText
drawPosText
enablesпозволяет eachпомещать characterзнак toна beопределенном placedпозиции. atНиже aслово specifiedfly
position.написано Below,на theразных wordпозициях flyY
.
val posArray = listOf(x1, y1, x2, y2, x3, y3 ...).toFloatArray()
canvas.drawPosText(TEXT, startIndex, endIndex, posArray, paint)
The
Приведенные coordinateкоординаты pointsточек needдолжны toбыть beкак atминимум leastкакие sameже asкак theбуквы lettersчтобы toнарисовать, beиначе drawn,они orупадут.
15. drawTextOnPath
Спаренные withс aпутем, path,мы weможем canуказывать positionнаш ourтекст textвдоль alongприведенного theпути.
providedx
path.и They
xпозиции andотносительно yпозиции positionsданного areпути.
canvas.drawTextOnPath(TEXT, path, x, y, paint)
Below
16. drawTextRun
This is a little more complicated, as it is generally not used with English words. It only applies to language with letters that are drawn differently depending on the visibility of surrounding letters. For example, the image below has two lines of two letters. The two letters in both lines are the same. However, they are written differently. In the first line, they are part of a larger word, while the second line states the two letters individually. Image for post To understand better, refer to this blog. Color Drawing Coloring is useful for the foreground and background of the canvas we’re drawing on. Check it out, as there’s a fancy one…
17. drawRGB
This is just drawing a color over the canvas. This is useful for setting a background color. canvas.drawRGB(red, green, blue) // Each is between 0 and 255, where 0 is not there, and 255 is full. // When alpha is 255, it is opaque, and 0 is transparent.
18. drawARGB
Similar to drawRGB, this adds the ability to make the color semi-transparent. canvas.drawARGB(alpha, red, green, blue) // When alpha is 255, it is opaque, and 0 is transparent. This is useful to set the front color and dim the item behind. Image for post Original Image Image for post Semi transparent red dimming the image
19. drawColor
In case we’d like to use a resource’s color instead of setting our own ARGB color, we can use this API. canvas.drawColor(context.getColor(R.color.colorPrimary))
20. drawPaint
Sometimes, we like to paint fancier colors. Instead of using ARGB or a resource color, we could create a Paint object. Below is an example:
val gradientPaint by lazy {
Paint().apply {
shader = RadialGradient(
width/2f,
height/2f,
height/2f,
Color.GREEN,
Color.RED,
Shader.TileMode.MIRROR
)
}
canvas.drawPaint(gradientPaint)
Image for post Image Drawing Without the ability to load images to draw and manipulate them, canvas drawing would be incomplete. So let’s explore what we have…
21. drawBitmap
Given a bitmap, we can draw it into the canvas.
private val bitmap by lazy {
BitmapFactory.decodeResource(resources, R.drawable.image)
}
canvas.drawBitmap(bitmap, sourceRect, destRect, paint)
The required parameters are bitmap and destRect. The bitmap can be extracted from resources. destRect is the rectangle area of the canvas to be drawn onto. The optional ones (could be null) are sourceRect and paint. sourceRect is a rectangle representing which subset of the picture to draw. When it is null, the entire picture is taken. (Note: this is very useful for some animation, when a picture of the entire animated drawing is added, and only a subset is shown at a time, as seen here.) paint could be set to null, and the Bitmap will still be drawn as usual. paint is useful if we plan to mask it out with another image. An example is shown in this StackOverflow.
22. drawPicture
If you have a combination of things to draw, and this happens multiple times, and you don’t want the processing to be slow and have to redraw them each tim, you could put your entire drawing into Picture. Below is a simple example where we store our drawing into a Picture:
private val picture by lazy {
val picture = Picture()
val pCanvas = picture.beginRecording(width, height)
pCanvas.drawBitmap(bitmap, null, rect, null)
picture.endRecording()
picture
}
When needed, just perform this: canvas.drawPicture(picture) This would speed up your entire process of drawing for things that need to be drawn over and over again.
23. drawBitmapMesh
This is to manipulate the bitmap image drawn. Given an image, we could set coordinates within the image, and translate a point to another position, hence transforming the image of it. E.g. the below image with the center X, Y is shown in the white line cross-section. Image for post However, using drawBitmapMesh, we could shift the coordinate and transform the image accordingly. Image for post Refer to this blog for more information. You can find all these code examples of Canvas drawing here. Have fun with Android Canvas Drawing!