Android Custom View 102
There is nothing new here, just another exercise.
Two things to be careful with:
Try to call validate() as fewer times as possible, it is expensive. If you want to handle the touch events in this manner, remember to return true from onTouchEvent(). Otherwise, only the first event will be triggered(most likely DOWN in this case) and not the succeeding ones (like the MOVES). Source Code
Let’s take a look at what we are going to build.
The secret is to clip canvas before drawing the text!
private fun drawText(canvas: Canvas, paint: Paint, start: Int, end: Int) { canvas.save() rect.set(start, 0, end, height) canvas.clipRect(rect) val textString = text.toString() paint.getTextBounds(textString, 0, textString.length, bounds) val x = width / 2 - bounds.width() / 2 val fontMetrics = changePaint.fontMetrics val dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.
Drawing text can be tricky at times, let’s look at some examples.
First, let’s look at some terminologies used here.
Some most important keywords are:
baseline: the line where the text “sits on” ascent: The recommended distance above the baseline for singled spaced text descent: The recommended distance below the baseline for singled spaced text top: The maximum distance above the baseline for the tallest glyph in the font at a given text size bottom: The maximum distance below the baseline for the lowest glyph in the font at a given text size A picture is worth 1000 words:
In this article we talk about drawing text.
Let’s see how to implement a view which simply displays some text. Let’s call it MyTextView.
This is how it will look like:
<!– Omitted constraintlayout related stuff–> <com.example.MyTextView.MyTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:background="@color/colorAccent" app:myTextColor="#000000" app:myText="Hello World! My love!" app:myTextSize="24sp" /> Let’s first define the custom attributes of the view, in values/attrs.xml
<resources> <declare-styleable name="MyTextView"> <attr format="string" name="myText" /> <attr format="color" name="myTextColor" /> <attr format="dimension" name="myTextSize" /> </declare-styleable> </resources> Then in the MyTextView.
In this article we talk about animation, specifically property animation.
ViewPropertyAnimator View has many properties, like position on screen, color and size. Property animation is the type of animation that animate on those properties.
In other words, the animator’s job is to set a specific set of properties of the view to different values many many times in a short period of time.
For example, the following code will move the view’s position 500px to the right: