Android Programming: 2D Drawing Part 1: Using ondraw



Similar documents
Android Programming Basics

Official Android Coding Style Conventions

Localization and Resources

Map Reduce Workflows

Hadoop Streaming coreservlets.com and Dima May coreservlets.com and Dima May

Advanced Java Client API

Apache Pig Joining Data-Sets

The Google Web Toolkit (GWT): The Model-View-Presenter (MVP) Architecture Official MVP Framework

Java with Eclipse: Setup & Getting Started

JHU/EP Server Originals of Slides and Source Code for Examples:

Android Programming: Installation, Setup, and Getting Started

HBase Java Administrative API

Virtual Machine (VM) For Hadoop Training

The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics

HBase Key Design coreservlets.com and Dima May coreservlets.com and Dima May

Hadoop Distributed File System (HDFS) Overview

Managed Beans II Advanced Features

For live Java EE training, please see training courses

Building Web Services with Apache Axis2

The Google Web Toolkit (GWT): Overview & Getting Started

Creating a 2D Game Engine for Android OS. Introduction

Session Tracking Customized Java EE Training:

HDFS - Java API coreservlets.com and Dima May coreservlets.com and Dima May

Mobile Application Frameworks and Services

Mobile App Tutorial Animation with Custom View Class and Animated Object Bouncing and Frame Based Animation

MMI 2: Mobile Human- Computer Interaction Android

Creating a List UI with Android. Michele Schimd

Android Introduction. Hello Mihail L. Sichitiu 1

Handling the Client Request: Form Data

HDFS Installation and Shell

Web Applications. Originals of Slides and Source Code for Examples:

Basic Java Syntax. Slides 2016 Marty Hall,

Intro to Android Development 2. Accessibility Capstone Nov 23, 2010

Now that we have the Android SDK, Eclipse and Phones all ready to go we can jump into actual Android development.

Mobile Application Development

Debugging Ajax Pages: Firebug

MapReduce on YARN Job Execution

! Sensors in Android devices. ! Motion sensors. ! Accelerometer. ! Gyroscope. ! Supports various sensor related tasks

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

Software Development Interactief Centrum voor gerichte Training en Studie Edisonweg 14c, 1821 BN Alkmaar T:

Object-Oriented Programming in Java: More Capabilities

Chapter 2 Getting Started

Hadoop Introduction coreservlets.com and Dima May coreservlets.com and Dima May

Lecture 1 Introduction to Android

directory to "d:\myproject\android". Hereafter, I shall denote the android installed directory as

Objective. Android Sensors. Sensor Manager Sensor Types Examples. Page 2

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Application Security

Web Applications. For live Java training, please see training courses at

Interactive Programs and Graphics in Java

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

Tutorial #1. Android Application Development Advanced Hello World App

AdFalcon Android SDK Developer's Guide. AdFalcon Mobile Ad Network Product of Noqoush Mobile Media Group

How to develop your own app

What servlets and JSP are all about

Frameworks & Android. Programmeertechnieken, Tim Cocx

IOIO for Android Beginners Guide Introduction

2011 Marty Hall An Overview of Servlet & JSP Technology Customized Java EE Training:

Boardies IT Solutions Tel:

TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION

Fireworks CS4 Tutorial Part 1: Intro

Mobile Application Development Android

Specialized Programme on Web Application Development using Open Source Tools

Getting Started: Creating a Simple App

Lab 1 (Reading Sensors & The Android API) Week 3

ART 170: Web Design 1

JSP Intro and Overview

Introducing Variance into the Java Programming Language DRAFT

Hello World! Some code

Fireworks 3 Animation and Rollovers

Servlet and JSP Filters

App Development for Smart Devices. Lec #4: Services and Broadcast Receivers Try It Out

Building and Using Web Services With JDeveloper 11g

"New Java course material and available pool of.ppt presentations"

Android Development. Marc Mc Loughlin

Android Environment SDK

Skills for Employment Investment Project (SEIP)

Fireworks for Graphics and Images

Animations in DrRacket

Introduction to Android SDK Jordi Linares

& JSP Technology Originals of Slides and Source Code for Examples:

Table of Contents. I. Banner Design Studio Overview II. Banner Creation Methods III. User Interface... 8

Introduction to Android Development. Daniel Rodrigues, Buuna 2014

Creating Java EE Applications and Servlets with IntelliJ IDEA

Advantages. manage port forwarding, set breakpoints, and view thread and process information directly

Introduction to NaviGenie SDK Client API for Android

ELET4133: Embedded Systems. Topic 15 Sensors

Event-Driven Programming

Admin. Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources. Recap: TinyOS. Recap: J2ME Framework

How To Write A Program For The Web In Java (Java)

Java (J2SE & J2EE) and Web Development Training Catalog

Sensors & Motion Sensors in Android platform. Minh H Dang CS286 Spring 2013

CSE476 Mobile Application Development. Yard. Doç. Dr. Tacha Serif Department of Computer Engineering Yeditepe University

Single Page Web App Generator (SPWAG)

Fundamentals of Java Programming

23442 ECE Introduction to Android Mobile Programming ECE Special Topics: Android Mobile Programming

AP Computer Science Java Subset

OUR COURSES 19 November All prices are per person in Swedish Krona. Solid Beans AB Kungsgatan Göteborg Sweden

Android Environment SDK

Transcription:

2012 Marty Hall Android Programming: 2D Drawing Part 1: Using ondraw Originals of Slides and Source Code for Examples: http://www.coreservlets.com/android-tutorial/ Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2012 Marty Hall For live Android training, please see courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this Android tutorial. Available at public venues, or customized versions can be held on-site at your organization. Courses developed and taught by Marty Hall JSF 2, PrimeFaces, servlets/jsp, Ajax, jquery, Android development, Java 6 or 7 programming, custom mix of topics Ajax courses Customized can concentrate Java on 1 EE library Training: (jquery, Prototype/Scriptaculous, http://courses.coreservlets.com/ Ext-JS, Dojo, etc.) or survey several Courses developed and taught by coreservlets.com experts (edited by Marty) Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Spring, Hibernate/JPA, EJB3, GWT, Hadoop, SOAP-based and RESTful Web Services Developed and taught by well-known Contact author hall@coreservlets.com and developer. At public for details venues or onsite at your location.

Topics in This Section Extending a View Using ondraw Referring to custom View in layout file Drawing basic shapes with Canvas Drawing bitmaps (images) with Canvas 5 2012 Marty Hall Extending a View Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary: Java 7 Idea Extend the View class, put the drawing code in ondraw Note: this assumes the View is placed in a fixed-size region. In lecture on Custom Components, we will discuss using onmeasure to calculate desired sizes. Syntax public class RandomShapeView extends View { protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.drawblah( ); Summary: XML 8 Idea Refer to the custom View with the view tag in layout file. Pass standard attributes (id, sizes, background). In lecture on Custom Components, we will discuss passing custom attributes. Syntax <view class="com.somecompany.somepackage.yourview" android:id=" " android:layout_width=" " android:layout_height=" " android:background=" " /> If you use regular (non-inner) classes, you can replace <view class="package.class" /> with <package.class />. However, this will not work with inner classes.

View Constructors ViewName(Context) Used when you directly call View constructor. Usually when you add View to Activity with setcontentview. public ViewName(Context context) { super(context); ViewName(Context, AttributeSet) Used when View built from layout XML file. Section on Custom Components will show how to use AttributeSet. public ViewName(Context context, AttributeSet attrs) { super(context); 9 Using ondraw: Canvas and Paint Canvas ondraw is passed a Canvas. Use its drawing methods. Paint Most of the drawing methods (drawarc, drawcircle, etc.) take a Paint as an argument. This is different from Swing and the AWT, where you set the paint on the Graphics separately from the drawing methods. The Paint also incorporates the font size Making a Paint Paint p = new Paint(); // Or Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); p.setcolor( ); p.settextsize( ); 10

Common Canvas Drawing Methods drawcolor, drawrgb, drawargb Fill entire region with a color. Note that this uses Color, not Paint. drawbitmap Draw a picture. Create a Bitmap from an image file via BitmapFactory.decodeResource (getresources(),r.drawable.blah) drawcircle, drawoval, drawrect, drawroundrect, drawarc, drawline Draw basic shape, usually inside rectangular region drawtext, drawtextonpath, drawpostext Draw text in simple or fancy ways. Note that drawpostext is deprecated in recent Android releases. drawpath A Path lets you combine multiple shapes into one object 11 Drawing Images 12 Put image files in res/drawable If file is res/drawable/foo_bar.gif, you will refer to it with R.drawable.foo_bar. You often want versions of your image in various resolutions, so you will put the images in res/drawable-xhdpi (extra high), res/drawable-hdpi (high), res/drawable-mdpi (medium), res/drawable-ldpi (low) Supported image types are jpeg, gif, png, bmp, and (Android 4.0+ only) webp Load image into Bitmap Bitmap pic = BitmapFactory.decodeResource (getresources(), R.drawable.base_name); Draw Bitmap canvas.drawbitmap(pic, left, top, null); The last arg is the Paint (null for opaque images)

Triggering Redrawing 13 Automatically After screen is rotated or covered and reexposed Manually Yes Call invalidate on the View If called by Thread other than main thread, you should call postinvalidate instead of invalidate No Call ondraw directly Very simple animation By repeatedly doing short Thread.sleep, then calling invalidate For details on fancier animation, see http://developer.android.com/guide/topics/graphics/index.html Avoid Allocating Drawing Objects in ondraw Idea ondraw is expensive ondraw can be called many times Consequence Don t allocate graphics objects in ondraw This is especially true of Bitmaps, but applies to Paint and other simpler objects as well 14

2012 Marty Hall Example: View that Draws Random Shapes Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Example Summary Idea Make View that draws random backgrounds, circles, rectangles, bitmaps, and text All sizes and locations based on current dimensions of the View View must go in fixed-sized region for now. We will discuss using onmeasure to request sizes in section on Custom Components Redrawing triggered by button in main Activity Gets id of custom View, calls findviewbyid, then calls invalidate on each button press 16

View: General Class Structure public class RandomShapeView extends View { private Integer[] mbackgrounds = { ; private Paint[] mforegrounds = { ; private Bitmap[] mpics = { ; private String mmessage = "Android"; To avoid repeated allocation, objects like Paint and Bitmap objects should be instantiated once per View instantiation (i.e., as instance variable values or in the constructor). 17 public RandomShapeView(Context context) { super(context); public RandomShapeView(Context context, AttributeSet attrs) { super(context, attrs); @Override protected void ondraw(canvas canvas) { super.ondraw(canvas); View: ondraw 18 public class RandomShapeView extends View { @Override protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.drawcolor(randomutils.randomelement(mbackgrounds)); int viewwidth = getwidth(); int viewheight = getheight(); int avgshapewidth = viewwidth/5; for(int i=0; i<20; i++) { drawrandomcircle(canvas, viewwidth, viewheight, avgshapewidth); drawrandomrect(canvas, viewwidth, viewheight, avgshapewidth); drawrandombitmap(canvas, viewwidth, viewheight); drawrandomtext(canvas, viewwidth, viewheight, avgshapewidth); You must call getwidth and getheight in ondraw (or after), not in the constructor. However, to avoid repeated allocation, real objects like Paint and Bitmap objects should not be instantiated in ondraw.

View: Random Background Colors public class RandomShapeView extends View { private Integer[] mbackgrounds = { Color.CYAN, Color.GRAY, Color.LTGRAY, Color.MAGENTA, Color.YELLOW, Color.WHITE ; @Override protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.drawcolor(randomutils.randomelement(mbackgrounds)); Notice that in Android, colors are really ints, as opposed to AWT and Swing where colors are real Objects. Also note that you draw backgrounds with colors, not Paints. 19 View: Random Circles public class RandomShapeView extends View { private Paint[] mforegrounds = { makepaint(color.black), makepaint(color.blue), makepaint(color.green), makepaint(color.red) ; private void drawrandomcircle(canvas canvas, int viewwidth, int viewheight, int avgshapewidth) { float x = RandomUtils.randomFloat(viewWidth); float y = RandomUtils.randomFloat(viewHeight); float radius = RandomUtils.randomFloat(avgShapeWidth/2); Paint circlecolor = RandomUtils.randomElement(mForegrounds); canvas.drawcircle(x, y, radius, circlecolor); 20 private Paint makepaint(int color) { Paint p = new Paint(); p.setcolor(color); return(p); drawrandomcircle is called from the loop in ondraw. Note that the Paint objects are not allocated in ondraw, but rather just once per class instantiation.

View: Random Rectangles public class RandomShapeView extends View { private Paint[] mforegrounds = { makepaint(color.black), makepaint(color.blue), makepaint(color.green), makepaint(color.red) ; private void drawrandomrect(canvas canvas, int viewwidth, int viewheight, int avgshapewidth) { float left = RandomUtils.randomFloat(viewWidth); float top = RandomUtils.randomFloat(viewHeight); float width = RandomUtils.randomFloat(avgShapeWidth); float right = left + width; float bottom = top + width; Paint squarecolor = RandomUtils.randomElement(mForegrounds); canvas.drawrect(left, top, right, bottom, squarecolor); 21 View: Random Bitmaps public class RandomShapeView extends View { private Bitmap[] mpics = { makebitmap(r.drawable.emo_im_angel), makebitmap(r.drawable.emo_im_cool), makebitmap(r.drawable.emo_im_crying), makebitmap(r.drawable.emo_im_happy), makebitmap(r.drawable.emo_im_yelling) ; There are versions of em_im_angel.png, emo_im_cool.png, etc., in res/drawable/xhdpi (extra-high dpi), res/drawable/hdpi (high dpi), res/drawable/mdpi (medium dpi), and res/drawable/ldpi (low dpi). Note again that the bitmaps are allocated once per View instantiation, not repeatedly in ondraw. 22 private void drawrandombitmap(canvas canvas, int viewwidth, int viewheight) { float left = RandomUtils.randomFloat(viewWidth); float top = RandomUtils.randomFloat(viewHeight); Bitmap pic = RandomUtils.randomElement(mPics); // Last arg is the Paint: you can use null for opaque images canvas.drawbitmap(pic, left, top, null); private Bitmap makebitmap(int bitmapid) { return(bitmapfactory.decoderesource(getresources(), bitmapid));

Random Text public class RandomShapeView extends View { private String mmessage = "Android"; private void drawrandomtext(canvas canvas, int viewwidth, int viewheight, int avgshapewidth) { float x = RandomUtils.randomFloat(viewWidth); float y = RandomUtils.randomFloat(viewHeight); float textsize = RandomUtils.randomFloat(avgShapeWidth); Paint textpaint = RandomUtils.randomElement(mForegrounds); textpaint.settextsize(textsize); canvas.drawtext(mmessage, x, y, textpaint); 23 Helper Class: Random Utilities public class RandomUtils { private static Random r = new Random(); public static int randomint(int range) { return(r.nextint(range)); public static int randomindex(object[] array) { return(randomint(array.length)); public static <T> T randomelement(t[] array) { return(array[randomindex(array)]); 24 public static float randomfloat(int n) { return((float)math.random()*n);

Layout File for Example (activity_draw_shapes1.xml) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > 25 <Button android:onclick="redraw" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/redraw_button_label" /> <view class="com.coreservlets.drawing.randomshapeview" android:id="@+id/drawing_area" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Activity for Example public class DrawShapes1 extends Activity { private RandomShapeView mdrawingarea; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_draw_shapes1); mdrawingarea = (RandomShapeView)findViewById(R.id.drawing_area); /** Handles events for the button. Redraws the ShapeView. */ public void redraw(view clickedbutton) { mdrawingarea.invalidate(); 26

Overall Main Layout File (main.xml) 27 <LinearLayout android:orientation="vertical"> <Button android:onclick="launchdrawshapes1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/random_shape_button_label" /> <Button android:onclick="launchrotate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/rotate_button_label" /> <Button android:onclick="launchskew" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/skew_button_label" /> <Button android:onclick="launchdrawshapes2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/shape_drawable_button_label" /> </LinearLayout> Overall Main Activity public class DrawingExampleLauncher extends Activity { @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); public void launchdrawshapes1(view clickedbutton) { Intent activityintent = new Intent(this, DrawShapes1.class); startactivity(activityintent); // Similar button-handling code for // other three drawing examples 28

Results 29 2012 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

References Android Dev Guide: Canvas & Drawables http://developer.android.com/guide/topics/graphics/ 2d-graphics.html Pro Android 3 (Komatineni et al) Chapter 16, Exploring 2D Animation Professional Android 4 (Meier) Creating New Views in Chapter 4 Enhancing Your Views in Chapter 11 Programming Android (Mednieks et al) Chapter 9, Drawing 2D and 3D Graphics 31 Summary 32 Java Extend View Make 2 constructors (Context and Context/AttributeSet) Override ondraw protected void ondraw(canvas canvas) { super.ondraw(canvas); canvas.drawblah( ); Avoid allocating Paint, Bitmap, etc. in ondraw XML <view class="com.somecompany.somepackage.yourview" android:id=" " android:layout_width=" " android:layout_height=" " android:background=" " />

2012 Marty Hall Questions? JSF 2, PrimeFaces, Java 7, Ajax, jquery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training. Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.