Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write text on an image

I can do this in Objective-C on the iPhone, but now I'm looking for the equivalent Android Java code. I can also do it in plain Java, but I don't know what the Android specific classes are. I want to generate a PNG image on the fly that has some text centered in the image.

public void createImage(String word, String outputFilePath){ 
    /* what do I do here? */ 
}

Relevant threads:

  • How to write text on image in Objective-C (iOS)?

  • How can I load an image and write text to it using Java?

like image 667
Ben Holland Avatar asked Jul 03 '12 19:07

Ben Holland


2 Answers

What about something like:

Bitmap bitmap = ... // Load your bitmap here
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(); 
paint.setColor(Color.BLACK); 
paint.setTextSize(10); 
canvas.drawText("Some Text here", x, y, paint);
like image 170
GETah Avatar answered Sep 22 '22 03:09

GETah


You don't need to use graphics.

A simpler approach would be to create a FrameLayout with two elements- the ImageView for the image, and another view for whatever you want drawn on top.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</FrameLayout>

Of course, the thing on top of the image doesn't need to be a simple TextView, it can be another image, or another layout containing whatever arbitrary elements you like.

like image 44
Jeffrey Blattman Avatar answered Sep 24 '22 03:09

Jeffrey Blattman