Android Project Scratch award details (iii)

Source: Internet
Author: User
Tags drawtext

Android Project Scratch award detailed (ii)


In the previous issue we have implemented a simple scratch card function, this issue we will improve it

    • Change the Scratch award width height to fit
    • Center The Scratch award position
    • Change the picture of the information layer to text (emphasis)

    1. Change the width of the scratch award to the appropriate height and center the Scratch award position

      In fact, it's very simple, we can change the size of layout directly, and use the modified position in the layout. gravity

       <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android=""     xmlns:app=""     xmlns:tools=""     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:gravity="center"     tools:context="com.wan.guajiang.MainActivity"> <com.wan.guajiang.GuaGuaKa      android:layout_width="300dp"      android:layout_height="100dp"/> </LinearLayout>
    2. Change the picture of the information layer into text

Before we draw the information layer is the winning picture, if there is no picture what to do? Of course, directly take the words to replace, canvas can not only draw pictures, but also can draw text, write text

First, let's look at the method parameters of the canvas drawText

drawText(String text, float x, floaty, Paint paint);

Text even if you want to write the text content, X, Y is the location of the write, it should be noted that the X, Y coordinates here is not the upper left corner of the text, but a closer to the lower left corner of the position. It's probably here:

The last parameter is the brush, which is similar to the previous one, and will be added later.

We want to write the text in the middle of the information layer, the coordinates of x, y, how to write it? As you can know, the canvas uses the drawText method, XY coordinates are actually located in the lower left corner of the text, is the diagram

Believe this picture is still very well understood, we continue to start writing code

  • First of all, we need a text content

      String message = "恭喜中奖,3万元!";
  • Define our brush paint and set it up

    Here we need a rect rectangle to get the background size of the text content, which is the red rectangle in the paint brush, which provides a way Gettextbounds , which we can use to get the background size of the text content
    Messagepaint.gettextbounds (String text,float start,float end, Rect rect);

    The above code means to intercept the length of the text from start to end, to form a rectangle with the length of the intercept and the height of the text, and the rect rectangle to receive the rectangle

      Rect mbackground = new rect ();//used to receive Gettextbounds returned by the rectangle paint messagepaint = new paint ();  Messagepaint.setcolor (;  Messagepaint.setantialias (TRUE);  Messagepaint.setstyle (Paint.Style.STROKE);  Messagepaint.gettextbounds (Message,0,message.length (), mbackground); Messagepaint.settextsize (+);  
  • calculates x, y coordinates, Canvas uses DrawText to write out text
    We have two ways to get the length and width of the black rectangle before, one is to use it getMeasured , the other is to use it mBitmap.get to get the length and width



    Test diagram

Full code
public class Guajiangview extends View {/** * Draws the paint of the line, where the user finger draws path */private Paint moutterpaint = new Pa    int ();    /** * Record User-drawn path */private path MPath = new Path ();    /** * Canvas created in memory */private canvas mcanvas;    /** * Mcanvas Draw content on it */private Bitmap mbitmap;    private int mlastx;    private int mlasty;    Private String message;//winning information private Rect mbackground;//text background rectangle size private Paint messagepaint = new paint ();//Text Brush    Private Boolean isclear = false;    Public Guajiangview (Context context) {super (context);    } public Guajiangview (context context, @Nullable AttributeSet attrs) {Super (context, attrs); } public Guajiangview (context context, @Nullable attributeset attrs, int defstyleattr) {Super (context, attrs, D    EFSTYLEATTR); } public Guajiangview (context context, @Nullable attributeset attrs, int defstyleattr, int defstyleres) {super ( Context, Attrs, defstyleattr, Defstyleres); } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (widthmeas        Urespec, Heightmeasurespec);        LOG.D (TAG, "onmeasure: Measurement");        int width = getmeasuredwidth ();        int height = getmeasuredheight (); Initialize Bitmap Mbitmap = bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888);//Create a 32-bit Bitmap MC with the obtained width and height Anvas = new canvas (MBITMAP);//Create a canvas Mcanvas.drawcolor ( with bitmap;//Set the color of the canvas to green mbackground = new R        ECT ();        Message = "Congratulations on winning, 30,000 Yuan!";        Messagepaint.setcolor (;        Messagepaint.setantialias (TRUE);        Messagepaint.setstyle (Paint.Style.STROKE);        Messagepaint.gettextbounds (Message,0,message.length (), mbackground);        Messagepaint.settextsize (30);        Set Brush Moutterpaint.setcolor (Color.Blue); Moutterpaint.setantialias (TRUE);//use antialiasing to consume larger resources, drawing graphics slower moutterpaint.setdither (true);//image jitter processing, Will make the painted picture color more smooth and full, the image is clearer       Moutterpaint.setstyle (Paint.Style.STROKE); Moutterpaint.setstrokejoin (Paint.Join.ROUND);//fillet, smooth moutterpaint.setstrokecap (Paint.Cap.ROUND); Fillet moutterpaint.setstrokewidth (20);    Sets the brush width messagepaint.setcolor (;        } @Override protected void OnDraw (canvas canvas) {LOG.D (TAG, "OnDraw: Painting"); Canvas.drawtext (Message,mbitmap.getwidth ()/2-mbackground.width ()/2,getmeasuredheight ()/2+mBackground.height ()/        2,messagepaint);        DrawPath ();    Canvas.drawbitmap (Mbitmap, 0,0, NULL);        } private void DrawPath () {LOG.D (TAG, "DrawPath:");        Moutterpaint.setxfermode (New Porterduffxfermode (PorterDuff.Mode.DST_OUT));    Mcanvas.drawpath (MPath, moutterpaint); } @Override public boolean ontouchevent (Motionevent event) {//When the finger is pressed on the screen, use the MoveTo method to move to the current position of the finger in the path, Inva Lidate Refresh view, callback OnDraw method, (not yet drawn)//After, the finger moves, the action is in Action_move state, the path path uses the LineTo method (draw a straight line),//At the same time, the x, y coordinates are updated, InvalidateRefresh view, callback OnDraw method, Canvas uses the brush to draw path through DrawPath, and then if the user does not lift the finger, continue to loop the steps in Action_move int action = Event.getaction (); int x = (int) event.getx ();//get x coordinate int y = (int) event.gety ();//Get y-coordinate switch (action) {CAs                e MotionEvent.ACTION_DOWN:mLastX = x;                Mlasty = y;            Mpath.moveto (MLASTX, mlasty);//After callback OnDraw method canvas will break path; Case MotionEvent.ACTION_MOVE:mPath.lineTo (x, y);//After callback OnDraw method, canvas draws a straight line to (x, y) that point mlastx = x            ;//update x coordinate mlasty = y;//update y-coordinate break;        Default:break;        } invalidate ();//Refresh view, callback OnDraw method Log.d (TAG, "ontouchevent:invalidate");    return true; }}
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.