"Android" itself defines the application of view, painter (canvas) canvas and brush paint--the implementation of the drawing and Doodle Board app

"Android" itself defines the application of view, painter (canvas) canvas and brush paint--the implementation of the drawing and Doodle Board app

Source: Internet
Author: User

Use a simple drawing app to illustrate Android's graphics-processing class with its own view-defining application.

For example, there is an app for users to draw and doodle at their own discretion.

It's not so fancy here, it's only available in black and white. But it can change the thickness of the nib.

Essentially the eraser here is a white brush, without using the brush's Setxfermode method, to get a bunch of complex project.

The user can save the image after drawing the picture. The file name of the image is the current time. The saved location is the root folder of the SDcard.

The production steps are as follows:

1, first set the font file Res\values\strings.xml, mainly the name of the app and the menu of the individual children of the characters.

<?xml version= "1.0" encoding= "Utf-8"?><resources> <string    name= "app_name" > Drawing </string>    <string name= "menu1" > Brush width </string>    <string name= "Menu1_sub1" >1</string>    <string name= "Menu1_sub2" >5</string>    <string name= "Menu1_sub3" >10</string>    < String Name= "Menu1_sub4" >50</string>    <string name= "menu2" > Brushes </string>    <string Name= "Menu3" > Eraser </string>    <string name= "Menu4" > Save </string>    <string name= "Menu5" > Exit </string>    <string name= "Menu_author" >yongh701</string></resources>
2, after the menu file settings, here no longer repeat, in the "Android" date picker, Time Picker and menu (click to open the link) and "Android" app transparency and font color notconsistent, context menu (click Open Link) two articles have specifically done menu things. Primarily the first menu option, "Brush width" is a subkey, so the ID of the Settings menu is set to the child item ID separately. Instead of the master item. The item does not need an ID.
<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:title= "@string/menu1"                    > <menu> <group android:checkablebehavior= "single" > <item                    Android:id= "@+id/menu1_sub1" android:title= "@string/menu1_sub1"/> <item Android:id= "@+id/menu1_sub2" android:title= "@string/menu1_sub2"/> &lt                ; Item android:id= "@+id/menu1_sub3" android:title= "@string/menu1_sub3"/>            <item android:id= "@+id/menu1_sub4" android:title= "@string/menu1_sub4"/> </group> </menu> </item> <item android:id= "@+id/menu2" Android: title= "@string/menu2"/> <item android:id= "@+id/menu3" android:title= "@string/menu3"/> <ite M android:id= "@+id/menu4"        android:title= "@string/menu4"/> <item android:id= "@+id/menu5" android:title= "@string/menu5" /> <item android:title= "@string/menu_author"/></menu>

3, because a moment also to the user to draw out the picture of the SDcard card, so will apply in the Androidmanifest.xml sdcard Write permission:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.painter "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk Android oid:minsdkversion= "8" android:targetsdkversion= "/><"!--need to write data on SD card--<uses-permission Androi D:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/> <application android:allowbackup=" true "android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <act Ivity android:name= "com.painter.MainActivity" android:label= "@string/app_name" > <i ntent-filter> <action android:name= "Android.intent.action.MAIN"/> <category and Roid:name= "Android.intent.category.LAUNCHER"/> &LT;/intent-filter> </activity> </application></manifest> 
4. Create a new view of your own definition, like the "Android" definition view, canvas canvas and brush paint (click to open link). This is Drawview. This drawview is the core of this app implementation. Its construction method, using the public drawview (context context, AttributeSet Attrs) {Super (context, attrs), this is a constructor with two parameters, For a moment this drawview will be placed directly in the mainactivity in XML form. At the same time through Alt+shift+s->v select inherit protected void OnDraw (canvas canvas) {},public boolean ontouchevent (Motionevent event) {} These two methods, one is the basic method of the Android image processing technology OnDraw, one is the user touches this view when the event Ontouchevent method occurs. At the same time, you add a Savebitmap method to achieve the last save of the picture.

The code for Drawview.java is as follows:

Package Com.painter;import Java.io.file;import Java.io.fileoutputstream;import java.text.simpledateformat;import Java.util.date;import Java.util.locale;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmap.config;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.path;import Android.os.environment;import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;import android.widget.Toast; public class Drawview extends View {private Bitmap cachebitmap;//paper private canvas cachecanvas;//create canvas, painter private Path path ///Drawing the path public paint paint;//Brush private float PreX, prey;//before the position of XY. Use the following gestures to move the private int view_width, view_height;//the height and width of the screen to public drawview (context context, AttributeSet Attrs) {super ( Context, attrs);p ath = new path ();p aint = new paint (); Cachecanvas = new Canvas ();//Gets the height and width of the screen view_width = Context.getreso Urces (). Getdisplaymetrics (). Widthpixels;view_height = context.getresources (). Getdisplaymetrics (). Heightpixels;cachebitmap = Bitmap.createbitmap (View_width, View_ height,config.argb_8888);//Create an image buffer to hold the image Cachecanvas.setbitmap (Cachebitmap); Cachecanvas.drawcolor (Color.WHITE); Paint.setcolor (Color.Black);//Set the brush's default color Paint.setstyle (Paint.Style.STROKE);//Set the brush to fill with no padding, But draw the line paint.setstrokewidth (1);//Set the brush width to 1} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); Canvas.drawbitmap (cachebitmap, 0, 0, paint);//Draw Cachebitmap to Drawview} @Overridepublic Boolean ontouchevent ( Motionevent event) {//Get touch position float x = Event.getx (); Float y = event.gety (); switch (Event.getaction ()) {//Get touch every instant case Mo tionevent.action_down://gestures Press Path.moveto (x, y);//Start point of drawing Prex = X;prey = y;break;case MotionEvent.ACTION_MOVE:float dx = M Ath.abs (X-prex); float dy = Math.Abs (Y-prey); if (dx > 5 | | dy > 5) {//user to move more than 5 pixels is a drawing. Lest hand slip, hand shake phenomenon path.quadto (PreX, PreY, (x + PreX)/2, (y + PreY)/2);p Rex = X;prey = Y;cachecanvas.drawpath (path, paint);//Draw Path}breakCase MotionEvent.ACTION_UP:path.reset (); Invalidate (); return true;} public void Savebitmap () throws Exception {String Sdpath = Environment.getexternalstoragedirectory (). GetAbsolutePath () ;//Gets the root path of the sdcard string filename = new SimpleDateFormat ("Yyyymmddhhmmss", Locale.getdefault ()). Format (New Date ( System.currenttimemillis ()));//generates a timestamp, called the file name, a filename, a document = new file (Sdpath + file.separator + filename + ". png"); file.create NewFile (); FileOutputStream FileOutputStream = new FileOutputStream (file); Cachebitmap.compress (Bitmap.CompressFormat.PNG, 100, FileOutputStream);//create png//with 100% quality Fileoutputstream.flush (); Fileoutputstream.close (); Toast.maketext (GetContext (), "image saved to" + Sdpath + file.separator + filename + ". png", Toast.length_short). Show ();}}

The whole Drawview.java did something like the following:

(1) Set a drawing cachebitmap. Two painters canvas and Cachecanvas, a paintbrush paint, here the reason to have two painters, is because the OnDraw method exclusive canvas This class member.

Every time the user touches the screen. Will trigger the Ontouchevent method. Set Cachecanvas to place the path drawn when the user touches the drawing cachebitmap. With the invalidate () method, the OnDraw method is called again, and Canvas puts the paper cachebitmap on the view of Drawview, which is our own definition.

The user will run this operation once per touch screen.

(2) because the invalidate () method is run each time. Will trigger the OnDraw method. So the initialization of the work should be placed in their own definition of the view of the construction method to save memory, this issue in the "Android" using its own definition of the view of the re-drawing implementation of drag movement, get the dimensions of the component (click the Open link) has been said, here no longer repeat. Construction method, complete painter (canvas) canvas with brush paint, paint path initialization.

The key is to put the original post-cachebitmap on the painter Cachecanvas hand, the same time command painter Cachecanvas This paper cachebitmap all painted white, that is, the drawing background color set to white. Otherwise, the background color of the image you saved will be black by default. Although you see your own definition of the view is white.

In the brush paint initialization thing, note to set the brush to Paint.setstyle (Paint.Style.STROKE), but the way to draw the edge, so talent to do the effect of graffiti, otherwise the brush default is, the attachment drawing rectangle kind of muddy effect.

(3) The method of drawing in touch event ontouchevent There is nothing to say here. The most important content in computer graphics. If you don't know, just copy it.

(4) The last method to save the image Savebitmap () There is nothing to say.

Is the operation of Android on the SDcard card, see "Android" read the picture on the SDcard (click Open link), and Java operation of the file, in detail, see "Java" Input and output and JDK1.5 after the new string StringBuilder " (Click to open the link).

5, through their own definition of view, can let Res\layout\activity_main.xml this mainactivity layout xml. The code with Mainactivity.java becomes concise.

Res\layout\activity_main.xml will become as short as the following. Just put a drawview, the implementation of everything in this own definition of the view is complete.

<framelayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent ">    <com.painter.drawview        android:id=" @+id/ DrawView1 "        android:layout_width=" match_parent "        android:layout_height=" Match_parent "/></ Framelayout>
6, finally in the Mainactivity.java to realize that the implementation of the various menus can be completed the entire App,oncreate method is nothing at all, but loaded into the layout file.
Package Com.painter;import Android.os.bundle;import Android.app.activity;import android.graphics.color;import Android.view.menu;import Android.view.menuitem;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} Handle Menu Event @overridepublic boolean onoptionsitemselected (MenuItem item) {Drawview Drawview = (drawview) Findviewbyid ( R.ID.DRAWVIEW1), switch (Item.getitemid ()) {//sets the method to run for the menu subkey with ID menu_exit.

Case R.id.menu1_sub1:drawview.paint.setstrokewidth (1); Break;case R.id.menu1_sub2:drawview.paint.setstrokewidth (5 ); Break;case r.id.menu1_sub3:drawview.paint.setstrokewidth (Break;case); R.ID.MENU1_SUB4: DrawView.paint.setStrokeWidth, Break;case R.id.menu2:drawview.paint.setcolor (color.black); break;case R.id.menu3:drawview.paint.setcolor (color.white); Break;case r.id.menu4:try {Drawview.savebitmap ();} catch ( Exception e) {e.printstacktrace ();} Break;case r.id.menu5:system.exit (0);//End program break;} return true;}}

At last. I uploaded a copy of the source code to everyone: http://download.csdn.net/detail/yongh701/8900457

"Android" itself defines the application of view, painter (canvas) canvas and brush paint--the implementation of the drawing and Doodle Board app

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.