Если вы видите что-то необычное, просто сообщите мне. Skip to main content

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категориям:

have
    experience
  • Геометрический makingрисование
  • custom
  • Текстовое views,рисование
  • you
  • Цветное canрисование
  • refer
  • Рисование toиз theкартинки.
  • tutorials
below:

На случай если у вас нет опыта создания своего 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повторять.
  • duplicate the… medium.com
  • 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

proandroiddev.com

Геометрицеское Geometricalрисование

Drawing

Множество Mostлюдей people useиспользует Canvas toдля drawрисования geometricalгеометрических items.объектов.

    1.
  1. drawLine
  2. Simply

    Просто drawрисует oneлинию

    line.
    canvas.drawLine(startX, startY, endX, endY, paint)
    Image
    for

    2. postdrawLines

  3. Если мы рисуем больше чем одну линию, взамен вызова 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)
    Image
    for post
  4. drawPoint While you could draw a point by drawing a line with the same start and end coordinates, this is considered a hack. So a

    3. drawPoint

    function

    Пока isвы provided.можете нарисовать точку с помощью линии с тем же началом и концом координат, то это можно считать хаком. Поэтому drawPoint функция существует.

    canvas.drawPoint(coordinateX, coordinateY, paint)
  5. 4. drawPoints

    As

    Как withв lines,случае youс canлиниями, drawвы multipleможете pointsнарисовать withмножество aточек flatс floatпомощью coordinateмассива array.координат.

    canvas.drawPoints(
        floatArrayOf(
            startX, startY,
            startSecondX, startSecondY),
        paint)
  6. 5. drawRect

    Draw

    Рисование aугла rectangleиспользя usingкоординаты coordinatesили orкласс aRect.

    Rect class.
    canvas.drawRect(
        Rect(startX, topY, endX, bottomY), 
        paint)
    Image
    for

    6. post

  7. drawRoundRect
  8. 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)
    It
    draws

    Функция 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 post
  9. drawCircle

    7. drawCircle

    is

    drawCircle simple.простой. ItЕму onlyтребуются requiresтолько theцентр centerкоординат coordinateи andрадиус.

    the radius.
    canvas.drawCircle(
        centerCoordinateX, centerCoordinateY,
        radius,
        paint)
    Image
    for

    8. post

  10. drawOval
  11. 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)
    Image
    for

    9. post

  12. drawArc
  13. 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)
    For
    the

    Для 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 = true
  14. drawPath Sometimes, we want to draw something that’s not restricted to normal geometrical lines. We use

    10. 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)
    Image
    for

    drawPath postочень drawPathполезная isфункция. aМного veryкто usefulиспользует function.её Manyдля useсоздания itнарисованных toприложений.

    make

    11. drawingdrawVertices

    app

    Это 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сложного thanks toмоделирования. MicrosoftКартинка Paint,ниже wellэто known3d asроза, simplyнарисованная Paintс orпомощью Paintbrush.drawVertices. ItВот wasдетальное a…объяснение medium.com

  15. его
  16. 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:

  17. прекрасный
  18. 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 canvas

    12. drawText

    comes

    На inандроиде, handy.мы Theобычно functionиспозуем follows,TextView withдля text,всех coordinate,наших andтекстов. paint:Однако, если мы хотели бы лучший контроль текста, такие как динамическое изменения, точное положение. и т.п., то нам поможет drawText. Функция принимает text, coordinateX, coordinateY и paint:

    canvas.drawText(text, coordinateX, coordinateY, paintText)
    These
    are

    Довольна funинтересная toфункция playчтобы withпоиграться ifс setней.

    correctly,

    13. as shown below: Image for post You can find more detail here.

  19. 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()

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.

is written at different Y positions. Image for post The API is below:
val posArray = listOf(x1, y1, x2, y2, x3, y3 ...).toFloatArray()
canvas.drawPosText(TEXT, startIndex, endIndex, posArray, paint)
The
provided

Приведенные coordinateкоординаты pointsточек needдолжны toбыть beкак atминимум leastкакие sameже asкак theбуквы lettersчтобы toнарисовать, beиначе drawn,они orупадут.

it will crash. The documentation notes: [This API is deprecated] because this method does not support glyph composition and decomposition and should therefore not be used to render complex scripts. It also doesn’t handle supplementary characters (eg emoji)

15. drawTextOnPath

Coupled

Спаренные withс aпутем, path,мы weможем canуказывать positionнаш ourтекст textвдоль alongприведенного theпути. providedx path.и They xпозиции andотносительно yпозиции positionsданного areпути.

relative to the position of the given path.
canvas.drawTextOnPath(TEXT, path, x, y, paint)
Below
is an example of a V-shaped path, and we draw our text along the path. Image for post

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!