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категориям:
На Drawingслучай Imageесли Drawingу Inвас caseнет youопыта don’tсоздания haveсвоего experienceview, makingвы customможете views,ссылаться youна canмануал referпод toназванием:
Introduction
Геометрицеское Geometricalрисование
Множество Mostлюдей people useиспользует Canvas toдля drawрисования geometricalгеометрических items.объектов.
1.
drawLineПросто drawрисует oneлинию
canvas.drawLine(startX, startY, endX, endY, paint)
Image
2. post
drawLines
Если мы рисуем больше чем одну линию, взамен вызова drawLine много раз, мы можем использовать drawLines. IfНам weнужно wantпредоставить toплоский drawмассив moreзначений thanкоординат aкак line,показано insteadниже.
canvas.drawLines(
floatArrayOf(
startFirstX, startFirstY, endFirstX, endFirstY,
startSecondX, startSecondY, endSecondX, endSecondY),
paint)
Image
3. drawPoint
Пока isвы provided.можете нарисовать точку с помощью линии с тем же началом и концом координат, то это можно считать хаком. Поэтому drawPoint функция существует.
canvas.drawPoint(coordinateX, coordinateY, paint)
4. drawPoints
Как withв lines,случае youс canлиниями, drawвы multipleможете pointsнарисовать withмножество aточек flatс floatпомощью coordinateмассива array.координат.
canvas.drawPoints(
floatArrayOf(
startX, startY,
startSecondX, startSecondY),
paint)
5. drawRect
Рисование aугла rectangleиспользя usingкоординаты coordinatesили orкласс aRect.
canvas.drawRect(
Rect(startX, topY, endX, bottomY),
paint)
Image
6. post
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угла.
canvas.drawRoundRect(rect, radiusX, radiusY, projectResources.paint)
It
Функция anрисует evenlyравномерно roundedкруглый cornerугол, ifесли radiusX equalsи radiusY.radiusY Imageравны.
7. drawCircle
drawCircle simple.простой. ItЕму onlyтребуются requiresтолько theцентр centerкоординат coordinateи andрадиус.
canvas.drawCircle(
centerCoordinateX, centerCoordinateY,
radius,
paint)
Image
8. post
drawOval
В Unlikeотличии drawingот aрисования circle,круга, weмы don’tне provideпредоставляем aрадиус. radius.Вместо Instead,этого weмы provideуказываем aпрямоугольник, rect,и andовал theбудет ovalнарисован willсоотвественно.
canvas.drawOval(rect, paint)
Image
9. post
drawArc
Рисование Drawingдуги anиспользует arcто usesчто theи sameовал: mechanismкласс asRect. drawingИ anимеет oval:дополнительные usingпараметры, aто Rect.есть ItstartAngle, hassweepAngle additionalи parameters,useCenter.
canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint)
For
Для startAngle,startAngle, countпочитаем theсередину middleконца endи ofпрямоугольник theкак rectначало, asто the start, i.e.есть 90° clockwise.поворот Fromпо there,часовой theстрелке. Отсюда начальный угол считается нулём. sweepAngle расчитывается от startAngle. is considered 0°TheОба sweepAngleиспользуют isзначения thenградусов calculatedугла.
fromuseCenter startAngle.это Bothбулева useпеременная theдля angleопределения degreeсвязана °арка value.с useCenterцентром.
10. drawPath
Иногда 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.
val path = Path()
path.moveTo(startX, topY)
path.lineTo(endX, bottomY)
path.moveTo(startX, bottomY)
path.lineTo(endX, topY)
canvas.drawPath(path, paint)
Image
drawPath postочень drawPathполезная isфункция. aМного veryкто usefulиспользует function.её Manyдля useсоздания itнарисованных toприложений.
11. drawingdrawVertices
Это programsотносительно inсложная Android.функция, Examplesкоторая below:рисует Aтреугольники guideили toвершины drawingс inмаленькими androidточками. IntroductionДля android.jlelse.euпримера, Learnс to6 createкоординатами, aможно Paintнарисовать Application4 forтреугольника.
AndroidПри Paintповторении, applicationsможно areиспользовать becomeдля famousсложного thanks3д toмоделирования. MicrosoftКартинка Paint,ниже wellэто known3d asроза, simplyнарисованная Paintс orпомощью Paintbrush.drawVertices.
ItВот wasдетальное a…объяснение medium.com
Text Drawing
Если weнам hadнужно toнарисовать drawтекст textсамостоятельно, ourselves,это thatбудет wouldдовольно beлегко. super-tricky.Благодаря Thankfully,тому, weчто haveмы severalимеем niceнесколько options:
12. drawText
На inандроиде, handy.мы Theобычно functionиспозуем follows,TextView withдля text,всех coordinate,наших andтекстов. paint:Однако, если мы хотели бы лучший контроль текста, такие как динамическое изменения, точное положение. и т.п., то нам поможет drawText.
Функция принимает text, coordinateX, coordinateY и paint:
canvas.drawText(text, coordinateX, coordinateY, paintText)
These
Довольна funинтересная toфункция playчтобы withпоиграться ifс setней.
13. as shown below:
Image for post
You can find more detail here.
У 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отрисовки:
val staticLayout =
StaticLayout.Builder.obtain(
TEXT, 0, TEXT.length, textPaint, width
).build()
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!