Draw text on Canvas

Description

The following code shows how to Draw text on Canvas.

Example

Main layout xml file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Main Activity Java code


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.widget.ImageView;
/*from   www  .  java2  s.  c  o m*/
public class MainActivity extends Activity {

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        
        Bitmap bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.RGB_565); 
        bitmap.eraseColor(Color.WHITE);
        Canvas canvas = new Canvas(bitmap); 
        
        Paint textPaint = new Paint(); 
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(24);
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Align.LEFT);
        
        canvas.drawText("Hello, Canvas!", 35F, 35F, textPaint);
        
        ImageView image = (ImageView) this.findViewById(R.id.imageView);        
        image.setImageBitmap(bitmap);        
    }
}
Draw text on Canvas




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView