แสดงบทความที่มีป้ายกำกับ Android graphics แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Android graphics แสดงบทความทั้งหมด

วันศุกร์ที่ 3 มกราคม พ.ศ. 2557

Android Graphics : Drawing Text


Android Graphics : Drawing Text

Loading Fonts
The Android API provides us with a class called Typeface that encapsulates a TrueType font. It provides a simple static method to load such a font file from the assets/

directory:
Typeface font = Typeface.createFromAsset(context.getAssets(), "font.ttf");

Interestingly enough, this method does not throw any kind of Exception if the font file can’t be loaded. Instead a RuntimeException is thrown. Why no explicit exception is thrown for this method is a bit of a mystery to me.

Drawing Text with a Font
Once we have our font, we set it as the Typeface of a Paint instance:
paint.setTypeFace(font);

Via the Paint instance, we also specify the size we want to render the font at:
paint.setTextSize(30);

The documentation of this method is again a little sparse. It doesn’t tell whether the text size is given in points or pixels. We just assume the latter.

Finally, we can draw text with this font via the following Canvas method:
canvas.drawText("This is a test!", 100, 100, paint);

MainActivity.java sourcecode


package android.graphics.drawText;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
           
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(new RenderView(this));
      }

      class RenderView extends View {
            Paint paint;
            //Typeface font;
            Bitmap icon;
            Rect bounds = new Rect();

            public RenderView(Context context) {
                  super(context);
                  paint = new Paint();
            }

            protected void onDraw(Canvas canvas) {
                             
                  paint.setColor(Color.BLUE);
                  paint.setTypeface(Typeface.SERIF);
                  paint.setTextSize(60);
                  paint.setTextAlign(Paint.Align.CENTER);              
                  canvas.drawText("Drawing Text Test", canvas.getWidth() / 2, 100,paint);
                  paint.setTextSize(42);
                  canvas.drawText("Paint.Align.CENTER", canvas.getWidth() / 2, 150,paint);
                 
                  String text = "Paint.Align.RIGHT.";
                  paint.setColor(Color.MAGENTA);
                  paint.setTextSize(42);
                  paint.setTextAlign(Paint.Align.RIGHT);               
                  paint.getTextBounds(text, 0, text.length(), bounds);
                  canvas.drawText(text, canvas.getWidth()/2, 250,paint);
                 
                  String text2 = "Paint.Align.LEFT.";
                  paint.setColor(Color.RED);
                  paint.setTextSize(42);
                  paint.setTextAlign(Paint.Align.LEFT);
                  paint.getTextBounds(text2, 0, text2.length(), bounds);
                  canvas.drawText(text2, canvas.getWidth() - bounds.width(), 350,paint);
                  invalidate();                
            }
      }
}

วันพฤหัสบดีที่ 2 มกราคม พ.ศ. 2557

Android Graphics : Drawing Bitmaps


Android Graphics : Drawing Bitmaps

Using Bitmaps
While making a game with basic shapes such as lines or circles is a possibility, it’s not exactly sexy. We want an awesome artist to create sprites and backgrounds and all that jazz for us, which we can then load from PNG or JPEG files. Doing this on Android is extremely easy.

Loading and Examining Bitmaps
The Bitmap class will become our best friend. We load a bitmap from a file by using the BitmapFactory singleton. As we store our images in the form of assets, let’s see how we can load an image from the assets/ directory:

InputStream inputStream = assetManager.open("android.png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

The Bitmap class itself has a couple of methods that are of interest to us. First we want
to get to know its width and height in pixels:

int width = bitmap.getWidth();
int height = bitmap.getHeight();

Drawing Bitmaps
Once we have loaded our bitmaps, we can draw them via the Canvas. The easiest method to do this looks as follows:

Canvas.drawBitmap(Bitmap bitmap, float topLeftX, float topLeftY, Paint paint);

The first argument should be obvious. The arguments topLeftX and topLeftY specify the coordinates on the screen where the top-left corner of the bitmap will be placed. The last argument can be null. We could specify some very advanced drawing parameters with the Paint, but we don’t really need those.

There’s another method that will come in handy, as well:

Canvas.drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint);

This method is super-awesome. It allows us to specify a portion of the Bitmap to draw via the second parameter. The Rect class holds the top-left and bottom-right corner coordinates of a rectangle. When we specify a portion of the Bitmap via the src, we do it in the Bitmap’s coordinate system. If we specify null, the complete Bitmap will be used.

Enum Values
Bitmap.Config ALPHA_8 Each pixel is stored as a single translucency (alpha) channel. 
Bitmap.Config ARGB_4444 This field was deprecated in API level 13. Because of the poor quality of this configuration, it is advised to use ARGB_8888 instead.  
Bitmap.Config ARGB_8888 Each pixel is stored on 4 bytes. 
Bitmap.Config RGB_565 Each pixel is stored on 2 bytes and only the RGB channels are encoded: red is stored with 5 bits of precision (32 possible values), green is stored with 6 bits of precision (64 possible values) and blue is stored with 5 bits of precision. 
Original on developer.android.com
http://developer.android.com/reference/android/graphics/Bitmap.Config.html

DrawingBitmapsActivity.java sourcecode

package android.example.drawingbitmap;

import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class DrawingBitmapActivity extends Activity {
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(new RenderView(this));      
    }

    class RenderView extends View {
      Bitmap cow_565;
      Bitmap android_8888;
      Bitmap icon;
      Rect dst = new Rect();
   
      public RenderView(Context context) {
            super(context);
     
            try {
                  // Read from res/assets/***.png
                  AssetManager assetManager = context.getAssets();
                 
                  InputStream inputStream = assetManager.open("cow.png");
                  cow_565 = BitmapFactory.decodeStream(inputStream);
                  inputStream.close();
                             
                  inputStream = assetManager.open("android_logo.png");
                  BitmapFactory.Options options = new BitmapFactory.Options();
                  options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                  android_8888 = BitmapFactory.decodeStream(inputStream, null, options);              
                  inputStream.close();
                 
                  // Read from Drawable
                  BitmapFactory.Options opt = new BitmapFactory.Options();
                  options.inJustDecodeBounds = true;
                  icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, opt);
                 
                 
            } catch (IOException e) {
                  // silently ignored, bad coder monkey, baaad!
            } finally {
                  // we should really close our input streams here.
            }
      }
           
      protected void onDraw(Canvas canvas) {
            dst.set(50, 50, 350, 350);
            canvas.drawBitmap(cow_565, null, dst, null);         
            canvas.drawBitmap(android_8888, 50, 400, null);
            canvas.drawBitmap(icon, 140, 750, null);
            invalidate();
      }
   
    } // RenderView
}




Download Android Graphics Drawing Bitmaps Example code

วันพุธที่ 1 มกราคม พ.ศ. 2557

Android Graphics : Drawing Shape




Android Graphics : Drawing Shape Example 

Draw your graphics directly to a Canvas. This way, you personally call the appropriate class's onDraw() method (passing it your Canvas), or one of the Canvas draw...() methods

On a View

If your application does not require a significant amount of processing or frame-rate speed (perhaps for a chess game, a snake game, or another slowly-animated application), then you should consider creating a custom View component and drawing with a Canvas in View.onDraw(). The most convenient aspect of doing so is that the Android framework will provide you with a pre-defined Canvas to which you will place your drawing calls.
Continuous Rendering in the UI Thread
All we’ve done up until now is set the text of a TextView when needed. The actual rendering has been performed by the TextView itself. Let’s create our own custom View whose sole purpose it is to let us draw stuff to the screen. We also want it to redraw itself as often as possible, and we want a simple way to perform our own drawing in that mysterious redraw method.
Although this may sound complicated, in reality Android makes it really easy for us to create such a thing. All we have to do is create a class that derives from the View class, and override a method called View.onDraw(). This method is called by the Android every time it needs our View to redraw itself. Here’s what that could look like:


class RenderView extends View {
      public RenderView(Context context) {
            super(context);
      }

      protected void onDraw(Canvas canvas) {
            // to be implemented
      }
}
Drawing Lines
To draw a line we can use the following Canvas method:

Canvas.drawLine(float startX, float startY, float stopX, float stopY, Paint paint);

The first two arguments specify the coordinates of the starting point of the line, the next two arguments specify the coordinates of the endpoint of the line, and the last argument specifies a Paint instance. The line that gets drawn will be one pixel thick. If we want the line to be thicker, we can specify its thickness in pixels by setting the stroke width of the

Paint:
Paint.setStrokeWidth(float widthInPixels);

Drawing Rectangles
We can also draw rectangles with the Canvas:

Canvas.drawRect(float topleftX, float topleftY, float bottomRightX, float bottomRightY,Paint paint);

The first two arguments specify the coordinates of the top-left corner of the rectangle,
the next two arguments specify the coordinates of the bottom-left corner of the rectangle, and the Paint specifies the color and style of the rectangle. So what can the style be and how do we set it?

To set the style of a Paint instance we call the following method:
Paint.setStyle(Style style);

Style is an enumeration that has the values Style.FILL, Style.STROKE, and Style.FILL_AND_STROKE. If we specify Style.FILL, the rectangle will be filled with the color of the Paint. If we specify Style.STROKE, only the outline of the rectangle will be drawn, again with the color and stroke width of the Paint. If Style.FILL_AND_STROKE is set, the rectangle will be filled, and the outline will be drawn with the given color and stroke width.

Drawing Circles
More fun can be had by drawing circles, filled or stroked, or both:

Canvas.drawCircle(float centerX, float centerY, float radius, Paint paint);

The first two arguments specify the coordinates of the center of the circle, the next argument specifies the radius in pixels, and the last argument is again a Paint instance. As with the Canvas.drawRectangle() method, the color and style of the Paint will be used to draw the circle.

One last thing of importance is that all these drawing methods will perform alpha blending. Just specify the alpha of the color as something other than 255 (0xff), and your pixels, lines, rectangles, and circles will be translucent.

MainActivity.java Source Code


package android.graphics.drawingshape;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawing_shape);
       
        LinearLayout container = (LinearLayout) findViewById(R.id.graphics);
        final RenderView aView = new RenderView(this);
        container.addView(aView);              
    }

    class RenderView extends View {
     
      Paint paint;
     
      public RenderView(Context context) {
            super(context);
            paint = new Paint();
           
            setFocusable(true);
            setFocusableInTouchMode(true);           
      }
     
      protected void onDraw(Canvas canvas) {
     
            // Draw Background Colour
            canvas.drawRGB(255, 255, 160);            // Yellow
           
            // Draw Line
            paint.setColor(Color.RED);
            canvas.drawLine(0, 0, canvas.getWidth()-1, canvas.getHeight()-1, paint);
           
            // Draw Circle
            paint.setStyle(Style.STROKE);
            paint.setColor(0xff000000);               // Black
            canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 80, paint);
           
            // Draw Rectangle
            paint.setStyle(Style.FILL);
            paint.setColor(0x770000ff);               // Blue                            
            canvas.drawRect(100, 100, 400, 400, paint);
            invalidate();
           
      }
    }
}


Layout xml Source code


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"      
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
        
    <LinearLayout
      android:id="@+id/graphics"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"/>

</LinearLayout>




Android Graphics : Drawing Shape Example Code