Drawing lines on android

How to draw Horizontal and Vertical lines in an Android App using XML

This article demonstrates how to draw a horizontal and a vertical line in an Android app.

Although we have countless XML tags to meet almost all of our needs, unfortunately, we don’t have any tag such as tag to draw the line. However, tag can be used in XML as a workaround.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

NOTE: The “view” tag is different than the View class in Android.

How to draw a Vertical line?
Consider the following XML code to draw a Vertical line in Android:

Here, we use the “View” tag to create a rectangle with a very small width such that it becomes a vertical line. In the above code, a red vertical line of height ‘560dp’ and width ‘2dp’ is drawn which is at a left margin of ‘175dp’ from the left side of the screen and at a top margin of ’20dp’ from the TextView that lies above it. The thickness of this line can be increased or decreased by increasing and decreasing the layout_width of the “View” tag respectively.

Note: To run this code, we can copy and paste this code into the XML Visualizer provided by Udacity. Make sure to erase all the previously written code in the visualizer(if any).

Output:

Drawing a Horizontal line:
A horizontal line can be drawn in a very similar way as a vertical line. Following is the XML code for a horizontal line:

Читайте также:  Android img repack tools cygwin

Источник

Drawing multiline text to Canvas on Android

Leveraging the Android framework and Kotlin to make Canvas text drawing more powerful

The Android Canvas offers a variety of drawing functions for implementing custom graphics in your app. A common use of Canvas is to draw text to a given region of a custom View , Drawable , Bitmap , etc.

Canvas has existing functions that allow you to draw text, the simplest of which can be seen below:

A single line of text is drawn at a given (x, y) origin, taking into account the properties of the Paint (to describe the colors and styles for the drawing eg. color , textSize , etc.). Other variants of this function exist that allow for specification of start and end positions within the text, drawing along a Path , etc.

The limitations of Canvas text drawing 🤨

The existing Canvas text drawing functions are simple and powerful but aren’t without their limitations. The major drawback (as mentioned above) is that the text is drawn on a single line. If the width of the text exceeds the width of the Canvas , the text will be clipped. Long text will usually need to be drawn on multiple lines, and you may have wanted “paragraph” style text in the first place. From here on, we’ll refer to this as multiline text.

How do we draw multiline text? 🤔

So how should we go about implementing this? Unfortunately you can’t just include \n characters in your text, as all whitespace characters are interpreted and drawn as spaces within the single line. Paint includes handy measureText and breakText functions for splitting up text which you could use. You may even consider an existing algorithm such as the Knuth-Plass Line Wrapping Algorithm. This quickly becomes a complex problem.

Android framework to the rescue 🚀

Thankfully, the Android framework provides us with a class that handles all of the complexity for us: Layout (in the android.text package), described as “a base class that manages text layout in visual elements on the screen”. It forms the basis of how classes like TextView fit text within given layout parameters.

Читайте также:  Последняя версия касперского для андроид

The documentation stipulates:

For text that will be edited, use a DynamicLayout , which will be updated as the text changes. For text that will not change, use a StaticLayout .

Considering that we are trying to draw some static (multiline) text to Canvas, StaticLayout is just what we need!

Using StaticLayout 👨‍💻

Using StaticLayout is quite simple. Firstly, instantiate one by obtaining and using a StaticLayout.Builder :

A few parameters are required when obtaining the builder:

  • text : The text CharSequence to be laid out, optionally with spans
  • start : The index of the start of the text
  • end : The index + 1 of the end of the text
  • textPaint : The TextPaint used for layout
  • width : The bounding width (in pixels)

These parameters allow StaticLayout to layout the text appropriately within the bounding width . A resultant height property becomes available once the StaticLayout has been instantiated. Many other parameters can be appended to the builder to adjust the end appearance, but we’ll get to those later.

Note: StaticLayout.Builder was added in API Level 23. Prior to this, you need to use the StaticLayout constructors. To add to this, the constructors have been deprecated in API Level 28. Be sure to handle backwards compatibility appropriately.

Note: If you happen to be utilising this in the onDraw function of a custom View , be sure to instantiate the StaticLayout separately to avoid object allocation during drawing (in a constructor or Kotlin init block, for example).

A word on TextPaint ☝️

Before we progress, there’s one thing that needs to be discussed… What is TextPaint ? While almost all Canvas functions require a Paint parameter, StaticLayout requires a TextPaint . From the documentation, it is described as “an extension of Paint that leaves room for some extra data used during text measuring and drawing”. A great explanation can be found here. In short, you use it exactly as you would Paint and don’t have to worry about the extra data it includes (for the purpose of what we are doing).

Exploring the StaticLayout properties 🔍

Phew! We now know the basics of what StaticLayout is and how we can use it to draw multiline text to Canvas . However, there are a lot of parameters that you can provide to change the appearance of the end result.

Читайте также:  Как распаковать прошивку андроид zip для чайников

Consider a basic text editor: you usually have options to change the alignment, margins, line spacing, text size and more. The same is true for StaticLayout ; additional parameters can be appended to the StaticLayout.Builder .

It is important to note that some parameters (like color ) do not belong directly to StaticLayout , but rather belong to the TextPaint . Let’s take a look at the some of the options we have:

alignment

The alignment of the text, similar to gravity.

Источник

Скачать Draw Lines на андроид v.1.3.9

Почему стоит скачать Draw Lines на андроид?

В этой мобильной игре вам предстоит пройти увлекательные уровни, рисуя различные фигуры для достижения цели. Главная цель – направить мяч в сторону монеты, чтобы перейти на следующий уровень. Чтобы сделать это, у игроков имеется возможность рисовать различные предметы, позволяющие достичь цели. Авторам удалось реализовать колоссальное количество уровней, что точно сможет увлечь игроков на долгое время, а также дать массу позитивных впечатлений от прохождения. Используйте нарисованные предметы, чтобы направить мяч в нужном направлении. В игре нет ограничений по времени, а также отсутствует необходимость в постоянном подключении к сети интернет, что позволяет играть в любое время, в любом месте. Если вы являетесь фанатом качественных головоломок, то вам точно стоит скачать Draw Lines на андроид.

Разработчикам удалось создать по-настоящему необычное и удобное управление, что позволяет с комфортом и интересом проходить захватывающие уровни. Простая главная цель и увлекательный геймплей является именно тем, что позволяет игре развлекать пользователей на протяжении многих часов. Играйте в свободное время, в любом месте, благодаря отсутствию необходимости в подключении к интернету. Рисуйте различные фигуры, чтобы доставить шар к монете и пройти уровень. Постепенный рост сложности добавляет интереса к прохождению, а также позволяет ощутить положительные эмоции при прохождении сложного уровня.

Чего интересного получают игроки от игры:

• Впечатляющее количество уровней;
• Захватывающий игровой процесс;
• Яркую и приятную прорисовку;
• Удобное управление;
• Необычный геймплей.

Чтобы заполучить отличную головоломку для смартфонов и планшетов, вам достаточно скачать Draw Lines на андроид. Источник: Плей Апк.

Источник

Оцените статью