Add text to image in android programmatically - android

I want to make an application just like opening screen of android.I am dynamically adding images to the rows of tableLayout. I have only defined tableLayout in xml file and remaining code is in java. I have added images successfully but i am not getting any help with setting text of that image (I want to display a text under image) and image to be a specific padding.How to do it?Thanks in advance.

Use the following function to write Text on Images:
private BitmapDrawable writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(convertToPixels(mContext, 11));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
//If the text is bigger than the canvas , reduce the font size
if(textRect.width() >= (canvas.getWidth() - 4)) //the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.setTextSize(convertToPixels(mContext, 7)); //Scaling needs to be used for different dpi's
//Calculate the positions
int xPos = (canvas.getWidth() / 2) - 2; //-2 is for regulating the x position offset
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos, paint);
return new BitmapDrawable(getResources(), bm);
}
public static int convertToPixels(Context context, int nDP)
{
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f) ;
}

What you can instead do is to put a TextView in overlay to a ImageView using a RelativeLayout :)

Here's Kotlin version Arun's solution:
import org.jetbrains.anko.dip
fun Context.writeTextOnDrawable(drawableId: Int, text: String) =
DrawableUtil.writeTextOnDrawableInternal(this, drawableId, text, 25, -2, 0)
object DrawableUtil {
fun writeTextOnDrawableInternal(context: Context, drawableId: Int, text: String,
textSizeDp: Int, horizontalOffset: Int, verticalOffset: Int): BitmapDrawable {
val bm = BitmapFactory.decodeResource(context.resources, drawableId)
.copy(Bitmap.Config.ARGB_8888, true)
val tf = Typeface.create("Helvetica", Typeface.BOLD)
val paint = Paint()
paint.style = Paint.Style.FILL
paint.color = Color.WHITE
paint.typeface = tf
paint.textAlign = Paint.Align.LEFT
paint.textSize = context.dip(textSizeDp).toFloat()
val textRect = Rect()
paint.getTextBounds(text, 0, text.length, textRect)
val canvas = Canvas(bm)
//If the text is bigger than the canvas , reduce the font size
if (textRect.width() >= canvas.getWidth() - 4)
//the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.textSize = context.dip(12).toFloat()
//Calculate the positions
val xPos = canvas.width.toFloat()/2 + horizontalOffset
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + verticalOffset
canvas.drawText(text, xPos, yPos, paint)
return BitmapDrawable(context.resources, bm)
}
}

I m successfully implemented such problem of adding text on image. Just look at following code. First of take one view as Relative layout in that layout take ImageView after that EditText and after that button. Give each of a id. Write a loadBitmapFromView function below.
public Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
and on click of button.
Bitmap bitmap = loadBitmapFromView(relativeLayout);
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "folderName");
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "capture.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Log.e("ExpressionEditImageActivity", "Error, " + e);
}
Enjoy...
For more reference, refer below screenshot:

Related

Full Text not showing into image

I am trying to convert text into image using below code :
public Bitmap textAsBitmap(String text, float textSize) {
Paint paint = new Paint(ANTI_ALIAS_FLAG);
paint.setTextSize(textSize);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setTextAlign(Paint.Align.CENTER);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(text) + 0.5f); // round
int height = (int) (baseline + paint.descent() + 0.5f);
Bitmap image = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, baseline, paint);
return image;
}
Its convert text into image but problem is show half text.It should show "favorite subject is english"!
what i am doing wrong ? or how should i solve this problem
Choose your width & height wisely,
Something like I did in my case
public Bitmap textAsBitmap(String text, float textSize) {
Paint paint = new Paint(ANTI_ALIAS_FLAG);
paint.setTextSize(textSize);
paint.setColor(Color.BLACK);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(text) + 0.0f); // round
int height = (int) (baseline + paint.descent() + 0.0f);
int actualWidth = width;
if (width > height)
height = width;
else
width = height;
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawText(text, width / 2 - actualWidth / 2, baseline, paint);
return image;
}
Problem is with paint.setTextAlign(Paint.Align.CENTER);, this property considers center as (0,0). So your text is actually at center according to (0,0).
Just remove paint.setTextAlign(Paint.Align.CENTER); and your code is working!!

How to show Android SeekBar progressChanged value inside SeekBar thumb?

I want to show the value of the current progress point in the thumb of an Android SeekBar. This is what I have tried so far:
SeekBar progBar = (SeekBar)FindViewById(Resource.Id.seekBar1);
progBar.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) =>
{
if (e.FromUser)
{
Drawable d = ContextCompat.GetDrawable(this, Resource.Drawable.thumb);
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.thumb);
Bitmap bmp = bitmap.Copy(Bitmap.Config.Argb8888, true);// this line gives me a System.NullReferenceException: Object reference not set to an instance of an object. error
Canvas c = new Canvas(bmp);
Canvas c = new Canvas(bmp);
string text = Integer.ToString(progBar.Progress);
Paint p = new Paint();
p.SetTypeface(Typeface.DefaultBold);
p.TextSize = 14;
p.Color = Color.White;
int width = (int)p.MeasureText(text);
int yPos = (int)((c.Height / 2) - ((p.Descent() + p.Ascent()) / 2));
c.DrawText(text, (bmp.Width - width) / 2, yPos, p);
progBar.SetThumb(new BitmapDrawable(Resources, bmp));
}
};
Then when I got the type of Drawable d, it's a Gradient Drawable. I researched but I couldn't find a way to convert a gradient Drawable to bitmap.
Drawable d = ContextCompat.GetDrawable(this, Resource.Drawable.thumb);
Canvas c = new Canvas();
Bitmap bitmap = Bitmap.CreateBitmap(d.IntrinsicWidth, d.IntrinsicHeight, Bitmap.Config.Argb8888);
c.SetBitmap(bitmap);
d.SetBounds(0, 0, d.IntrinsicWidth, d.IntrinsicHeight);
d.Draw(c);
//Bitmap bmp = bitmap.Copy(Bitmap.Config.Argb8888, true);
string text = Integer.ToString(progress) + "%";
Paint p = new Paint();
p.SetTypeface(Typeface.CreateFromAsset(Assets, "fonts/Brandon_bld.otf"));
p.TextSize = 18;
p.Color = Color.White;
int width = (int)p.MeasureText(text);
int yPos = (int)((c.Height / 2) - ((p.Descent() + p.Ascent()) / 2));
c.DrawText(text, (bitmap.Width - width) / 2, yPos, p);
progBar.SetThumb(new BitmapDrawable(Resources, bitmap));
using the canvas to create the bitmap worked

How to show a Text Between a Line in Google map

I am displaying two points in google-map. and draw a line between two points. Now i have distance value and want to display at center of line.
what should i need to do?
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(geo, new LatLng(28.549961,77.4107057))
.width(2)
.color(Color.BLUE).geodesic(true));
Above it the code of draw a line
Create a Png with a invisible background and import it to your drawable folder. After that use this code:
obm = writeTextOnDrawable(R.drawable.text_background, yourtexthere);
LatLng point=new LatLng((latitude1+latitude2)/2,(longitude1+longitude2)/2);
MarkerOptions markerOptions = new MarkerOptions().icon(
BitmapDescriptorFactory.fromBitmap(obm))
.position(point);
mMap.addMarker(markerOptions));
private Bitmap writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setColor(Color.BLACK);
paint.setTypeface(font);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(convertToPixels(this, 11));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
// If the text is bigger than the canvas , reduce the font size
if (textRect.width() >= (canvas.getWidth() - 4)) // the padding on
// either sides is
// considered as 4,
// so as to
// appropriately fit
// in the text
paint.setTextSize(convertToPixels(this, 7)); // Scaling needs to be
// used for
// different dpi's
// Calculate the positions
int xPos = (canvas.getWidth() / 2) - 2; // -2 is for regulating the x
// position offset
// "- ((paint.descent() + paint.ascent()) / 2)" is the distance from the
// baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint
.ascent()) / 2));
canvas.drawText(text, xPos, yPos, paint);
return bm;
}
public static int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources()
.getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
edit the yourtexthere and point variables and the png resource name to your liking
You could use a custom marker that you set where you need it to be. You'll have to figure out an algorithm for that.

How To add caption with image share on instagram in android?

This is my code. i want to Add caption with image. Please help me.
private void shareInstagram(Uri uri){
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*"); // set mime type
shareIntent.putExtra(Intent.EXTRA_STREAM,uri); // set uri
shareIntent.putExtra(Intent.EXTRA_TITLE, "Sample title");
shareIntent.setPackage("com.instagram.android");
startActivity(shareIntent);
}
you should write caption on image and then create uri.
private Bitmap writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(convertToPixels(mContext, 11));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
//If the text is bigger than the canvas , reduce the font size
if(textRect.width() >= (canvas.getWidth() - 4)) //the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.setTextSize(convertToPixels(mContext, 7)); //Scaling needs to be used for different dpi's
//Calculate the positions
int xPos = (canvas.getWidth() / 2) - 2; //-2 is for regulating the x position offset
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos, paint);
BitmapDrawable bmd = new BitmapDrawable(getResources(), bm);
Bitmap newbit;
newbit=bmd.getBitmap();
return newbit;
}
public static int convertToPixels(Context context, int nDP)
{
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f) ;
}
ref : Add text to image in android programmatically
Save Bitmap to file :
Save bitmap to file function
create uri from file :
Uri.fromFile(new File(<your image absolute path>));
Then pass this uri to your function
private void shareInstagram(Uri uri){
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*"); // set mime type
shareIntent.putExtra(Intent.EXTRA_STREAM,uri); // set uri
shareIntent.putExtra(Intent.EXTRA_TITLE, "Sample title");
shareIntent.setPackage("com.instagram.android");
startActivity(shareIntent);
}
Hope it should work

Android - Converting string to image

I need to read the text/string from database and convert them into images. I tried the following code but I am getting only blank images. Please help
public Bitmap textAsBitmap(String text, float largest, int textColor) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(textColor);
// int width = (int) (paint.measureText(text) + 0.5f); // round
paint.setAntiAlias(true);
paint.setTypeface(Typeface.MONOSPACE);
paint.setTextSize(16);
int width = 400;
// float baseline = (int) (paint.ascent() + 0.5f) + 3f;
// int height = (int) ((baseline + paint.descent() + 0.5f) + 3);
int height = 400;
Bitmap image = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, 5, paint);
return image;
}
I haven't tried this, but do you perhaps need to first fill your bitmap with a colour that contrasts with textColor? This would certainly seem like an important thing to do in any case -- the documentation for createBitmap() does not specify the initial content of the bitmap, so it could theoretically be anything, and may change in future versions of the system.

Categories

Resources