Ben Holland
Ben Holland

Reputation: 2329

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:

Upvotes: 7

Views: 24020

Answers (3)

Skoua
Skoua

Reputation: 3603

GETah's answer wasn't working for me so I tweeked it a bit, here's a Kotlin version, which works, using TextPaint:

val canvas = Canvas(bm)
val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.LINEAR_TEXT_FLAG)
textPaint.style = Paint.Style.FILL
textPaint.color = Color.BLACK
textPaint.textSize = 30f
canvas.drawText("Hello", 50f, 50f, textPaint)

Upvotes: 0

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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.

Upvotes: 7

GETah
GETah

Reputation: 21409

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);

Upvotes: 23

Related Questions