Android custom view, drawing with Ontouchevent event (one)

Source: Internet
Author: User
Tags drawtext gety
<span id="Label3"></p>Drawing construction methods<p><p>Custom view needs to inherit the view class, overriding two construction methods</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Used in the code new view object, Initialize public MyView (context Context) {super (context); init ();} General add Construction---"view put into the layout, the system instantiates public MyView (context context, attributeset attrs) {super (context, attrs); init ();}</pre></pre><br><p><p></p></p>Paint Object<p><p></p></p><p><p>Drawing a view requires the use of a paint object, which is equivalent to a Brush. Initialization requires some properties to be set for this Brush.</p></p><p><p><br></p></p><p><p><br></p></p><p><p>With the paint instantiated, The comments are written clearly and there are three common initialization methods:</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">private void init () {paint=new paint ();//set The brush's color Paint.setcolor (color.green);//antialiasing, Improve the quality of the drawing Paint.setantialias (true); /set Brush style, Hollow Paint.setstyle (style.stroke);}</pre></pre><br><p><p></p></p>Rewrite OnDraw ()<p><p></p></p>Common Image Drawing <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> To draw a graphic, you have at least three objects: <span style="white-space:pre"> </span>1. Color object colour <span style="white-space:pre"> </span>2. Brush object paint <span style="white-space:pre"> </span>3. Canvas object Canvases <br> </blockquote> </blockquote><br><p><p><span style="white-space:pre"></span>In order to draw a custom view, you need to override the OnDraw () method, parameter: (canvas Canvas) is a canvas object, which is drawn in this Canvas.</p></p><p><p>The following shows the process of drawing rectangles, circles, text, pictures, lines, and arcs, where the process of drawing an arc depends on the rectangle, which is somewhat different from the Others.</p></p><p><p><br></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Declares a Rectangle object (in order to draw an Arc) private RECTF rectf; @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); rectf=new RECTF (10, 10, 70, 60);//instantiate rectangle//draw rectangle <span style= "white-space:pre" ></span>//canvas.drawrect (10, 10, 70, 60, paint), in both ways, if the first sentence is not declared recf, it is plotted by constructing multiple Parameters. <span style= "white-space:pre" ></span>canvas.drawrect (rectf, paint);//draw arc canvas.drawarc (rectF, 0, 290, true, paint);//draw a circle: parameter 1, 2: The coordinate parameter of the center of the circle 3: radius canvas.drawcircle (+,, paint);//picture <span style= "white-space:pre "></span> Picture Resource <span style=" white-space:pre "></span> coordinates (x, y) canvas.drawbitmap the upper-left corner of the picture ( Bitmapfactory.decoderesource (getresources (), r.drawable.ic_launcher), (+), $, paint);//draw text <span style= " White-space:pre "></span> text in the upper left corner of the coordinates canvas.drawtext (" Nihaohao ", The x, the Paint);//draw line <span style=" White-space:pre "></span> Start coordinates the focus coordinates of the paint object Canvas.drawline (205, 305, 255, 355, paint);}</pre></pre><br><p><p></p></p><span style="color:#ff0000"><span style="color:#ff0000">Paintings <shape> Objects</span></span><p><p></p></p><p><p>Drawing of a Shape object</p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html"><shape xmlns:android= "http://schemas.android.com/apk/res/android" android:shape= "oval" > <size Android:width= "60px" android:height= "60px" ></size> <stroke android:color= "#ff0000" android:width= "2px" ></stroke> <gradient android:startcolor= "#ff0000" android: centercolor= "#00ff00" android:endcolor= "#0000ff" ></gradient></shape></pre></pre><p><p></p></p><p><p><br></p></p>Initialize method initial drawable, This get to is a Drawable object<br><pre name="code" class="java"><pre name="code" class="java">private void init () {drawable = getresources (). getdrawable (r.drawable.cir);}</pre></pre>In the OnDraw () method, the notes are clear.<p><p></p></p><pre name="code" class="java"><pre name="code" class="java">protected void OnDraw (canvas canvas) {super.ondraw (canvas);//set drawable bounds specify x,yrect bounds = Drawable.getbounds (); Bounds.left = (int) X;bounds.top = (int) y;bounds.right = bounds.left + 60;//just guarantee a certain distance from the boundary bounds.bottom =bounds.top + 60;dra Wable.setbounds (bounds);//draw to canvas on Drawable.draw (canvas);}</pre></pre><br><p><p></p></p><span style="color:#ff0000"><span style="color:#ff0000">Draw Bitmap Objects</span></span><p><p></p></p><p><p>In the Init () method</p></p> <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> <p> </p> <pre name="code" class="java">Bitmap=bitmapfactory.decoderesource (getresources (), r.drawable.ic_launcher);</pre> <p> </p> </blockquote> </blockquote><p><p><span style="white-space:pre"></span>OnDraw () method, It should be noted that the Drawbitmap () method parameter, parameter one: Bitmap object <span style="white-space:pre"></span> parameter two: bitmap upper left corner x coordinate <span style="white-space:pre"></span> parameter three: bitmap upper left corner y Coordinate. So if you want the coordinates to be specified in the middle of the picture, you need x-bitmap.getwidth ()/2, y-bitmap.getheight ()/2. <span style="color:#ff0000">The advantage of this is</span> that in the ontouchevent () event, the defined x, y coordinates can be set in the middle of the picture, completing certain gesture Actions.</p></p><p><p><span style="white-space:pre"></span></p></p><pre name="code" class="java"><pre name="code" class="java">Canvas.drawbitmap (bitmap, x-bitmap.getwidth ()/2, y-bitmap.getheight ()/2, paint);</pre></pre><br><span style="white-space:pre"><span style="white-space:pre"></span></span>Also note: the order is not reversed. is to draw on canvas instead of this canvas to draw other Objects. Canvas is in a<span style="color:#ff0000"><span style="color:#ff0000">the passive</span></span>Angle.<br><br><p><p></p></p><p><p><br></p></p>Ontouchevent<p><p>This method responds to events that occur on the touch screen, including pressing, lifting, moving, and so on, which can be heard by the Monitor.</p></p><p><p>can achieve a certain drag, drawing Function. Through the event can get to these actions and the current x, y coordinates and so On.</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">public boolean ontouchevent (motionevent Event) {//this method often needs to redraw the interface, using this method to automatically invoke the OnDraw () method. (main thread) invalidate ();//non-ui thread with Postinvalidate ();//causes the system to respond to events, returning Truereturn true;}</pre></pre><br>Three ways of judging and handling events:<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">public boolean ontouchevent (motionevent Event) {//gets The coordinates of the finger on the screen float x = event.getx (); float y = event.gety ();//get finger operation--" press, move, Release int action = event.getaction (), switch (action) {case motionevent.action_down://press log.i (TAG, "action_down"); Break;case motionevent.action_move://mobile log.i (tag, "action_move"); break;case motionevent.action_up://release log.i (tag, " Action_up "); break;} Return true;}</pre></pre><br><span style="white-space:pre"><span style="white-space:pre"></span></span>and through x, y coordinates can judge the direction of the slide, so make some judgments, can respond to animation, scrollview and so on, can do a lot of things. however, Some complex gesture operations require Android Gesturedetector. For example, double-click, Fling and other more complex gestures. This class is summed up after two days. When handling touch events, activity first responds to Ontouchevent ().<p><p></p></p><p><p><br></p></p>A demo: artboards<p><p><br></p></p><p><p></p></p><pre name="code" class="java">public class Writepadview extends View{//view is placed in the layout,, instantiate public writepadview (context context, attributeset attrs) {super ( context, attrs); Init ();} Code new control public Writepadview (context Context) {super (context); init ();} private void init () {linesx=new arraylist<arraylist<float>> (); linesy=new arraylist<arraylist< float>> ();p aint=new Paint ();//set The color paint.setcolor (color.green);//set anti-aliasing paint.setantialias (true);// Sets the style of the brush Paint.setstyle (style.fill);} Draw view @overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); for (int j=0;j<linesx.size (); j + +) {// Connect dots into line 3for (int i=0;i<linesx.get (j). size () -1;i++) {canvas.drawline (linesx.get (j). get (i), linesy.get (j). get (i), Linesx.get (j). get (i+1), linesy.get (j). get (i+1), paint);}} /** two sets--"point---of the locus of the finger" a segment */private arraylist<float> xs, ys;private paint Paint;//set of all segments private list< arraylist<float>> Linesx,linesy;//finger Touch Screen @overridepublic boolean ontouchevent (motionevent event) {// Get the position of the finger float x = event.getx (); FloaT y = event.gety (); if (event.getaction () ==motionevent.action_down) {//press--"a new segment begins xs=new arraylist<float> (); Ys=new arraylist<float> (); linesx.add (xs); linesy.add (ys);} Record the position of the finger xs.add (x); ys.add (y);//notification view redraw, invalidate (); return true;}}</pre><br><br><p><p></p></p><p><p><br></p></p>Custom View load to view<p><p>In the layout xml, use the custom view to refer <span style="white-space:pre"></span> to the <span style="color:#ff0000">package Name. class Name.</span> <span style="color:rgb(255,0,0); white-space:pre"></span></p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html"> <com.bless.myviewdemo.myview android:layout_width= "wrap_content" android:layout_height= "wrap_ Content "/></pre></pre><br><p><p></p></p><p><p><br></p></p>Some property methods are attached to the paint object:<p><p>Paint:<br>void Setargb (int a, int r, int g, int B) Sets the Paint object color, parameter one is Alpha transparent channel<br><br>void Setalpha (int A) sets Alpha opacity with a range of 0~255<br><br>void Setantialias (boolean Aa)//whether anti-aliasing<br><br>void SetColor (int Color)//set color, here the Android internal definition has a color class containing some common color definitions<br><br>void Setfakeboldtext (boolean fakeboldtext)//set pseudo-bold text<br><br>void Setlineartext (boolean Lineartext)//set linear text<br><br>Patheffect setpatheffect (patheffect effect)//set Path effect<br><br>Rasterizer Setrasterizer (Rasterizer Rasterizer)//set rasterization<br><br>Shader Setshader (Shader Shader)//set Shadow<br><br>void settextalign (paint.align Align)//set text alignment<br><br>void Settextscalex (float scaleX)//set text magnification, 1.0f to original<br><br>void settextsize (float textSize)//set font size<br><br>Typeface settypeface (Typeface Typeface)//set The font, Typeface contains the type of font, weight, and tilt, color, and so On.<br><br>void Setunderlinetext (boolean Underlinetext)//set underline<br></p></p><p><p><br></p></p>Canvas with Canvas properties:<br>void DrawRect (RECTF rect, paint paint)//plot area, parameter one for RECTF one area<br><br>void DrawPath (path path, paint Paint)//draw a path, parameter<br><br>void Drawbitmap (Bitmap Bitmap, rect src, rect dst, Paint paint)//map, parameter One is our regular Bitmap object, parameter two is the source area (here is Bitmap), The parameter three is the target area (should be in The position and size of the canvas), parameter four is the paint brush object, because it is possible to scale and stretch, and when the original rect is not equal to the target rect, there is a significant loss of performance.<br><br>void DrawLine (float startX, float starty, float stopx, float stopy, paint Paint)//draw line, The x-axis position of a starting point of the parameter, the y-axis position of the parameter two starting point, the x-axis horizontal position of the Parameter's three endpoints The vertical position of the parameter four y axis, and the last parameter is the paint brush object.<br><br>void Drawpoint (float x, float y, paint Paint)//draw point, parameter one horizontal x axis, parameter two vertical y axis, third parameter is paint Object.<br><br>void DrawText (string text, float x, float y, paint Paint)//render text, Canvas class In addition to the above can also depict text, parameter one is a String type of text, parameter two x axis, parameter three y axis, Parameter four is the paint object.<br><br>void Drawtextonpath (String text, path path, float hoffset, float vOffset, paint paint)//draw text on path, relative to the second parameter above is the path path object<br><br>Original address of the Appendix: http://blog.csdn.net/listening_music/article/details/6859229<p><p>Android custom view, drawing with Ontouchevent event (one)</p></p></span>
Related Article

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.