Issues in put Multiple Texts with Image using canvas and paint - android

here is my code :
ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
// Bitmap bmp =drawTextToBitmap(this,R.drawable.man,"Hello Android");
Bitmap bmp =drawTextArrayToBitmap(this,R.drawable.man,"Smile");
mImageView.setImageBitmap(bmp);
now here is my method :
public Bitmap drawTextArrayToBitmap(Context mContext, int resourceId,String mText) {
try {
Resources resources = mContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(110,110, 110));
paint.setTextSize((int) (12 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
/* int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;*/
int x = 100, y = 100;
for(int i=0;i<20;i++)
{
canvas.drawText(mText, x * scale, y * scale, paint);
}
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
I am working on an android application like image filter I want to make an image like this after using a filter over an image
After searching on StackOverflow I got this solution only and this is not like as I want to implement: I got like this
canvas.drawText("This is", 100, 100, mTextPaint);
canvas.drawText("multi-line", 100, 150, mTextPaint);
canvas.drawText("text", 100, 200, mTextPaint);
I do not want to do like this : please help me I would approciate your answers and suggestion

Related

How to pass many textview on random position over image view?

now I am getting only one Text over the image I am using Canvas and Bitmap :
here is my code :
public Bitmap drawTextArrayToBitmap(Context mContext, int resourceId,String mText) {
try {
Resources resources = mContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(110,110, 110));
paint.setTextSize((int) (12 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
/* int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;*/
int x = 100, y = 100;
for(int i=0;i<20;i++)
{
canvas.drawText(mText, x * scale, y * scale, paint);
}
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
inside oncreate ;
ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
// Bitmap bmp =drawTextToBitmap(this,R.drawable.man,"Hello Android");
Bitmap bmp =drawTextArrayToBitmap(this,R.drawable.man,"Smile");
mImageView.setImageBitmap(bmp);
In this above code, I want to add multiple texts on random position over Image and different style I have tried much time I could not get succeed yet. I have tried inside loop also.
Thank you in Advance I would appreciate your effort

how to put text on image bitmap at bottom?

What I Want: I want to add text at bottom of a image which I have chose from either gallery or camera.
Original Image
I added blue color strip to image at bottom
In that strip, I want to add some text exactly in middle.
What's the Problem:
I'm unable to position text exactly in middle of blue color strip.
For different images, text size changes. Some time it is very small, some time it is very big.
What I Tried: My code is like below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
}
public void openGallery(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 100);
}
public void openCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 101);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && resultCode == Activity.RESULT_OK) {
if (requestCode == 100) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media
.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
addStampToImage(bitmap);
} else if (requestCode == 101) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
addStampToImage(bitmap);
}
}
}
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
Paint pText = new Paint();
pText.setColor(Color.WHITE);
pText.setTextSize((int) (20 * scale));
String text = "Maulik";
/*Rect r = new Rect();
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
pText.setTextAlign(Paint.Align.LEFT);
pText.getTextBounds(text, 0, text.length(), r);
float x = -r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
int minusSpace = (int) (canvas.getClipBounds().bottom * 0.07);
canvas.drawText(text, 0, canvas.getClipBounds().bottom - minusSpace, pText);*/
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
int x = (newBitmap.getWidth() - bounds.width())/6;
int y = (newBitmap.getHeight() + bounds.height())/5;
canvas.drawText(text, x * scale, y * scale, pText);
mImageView.setImageBitmap(newBitmap);
}
}
Any help will be appreciated!
Updated: 1st Aug 2018
Changes in addStampToImage method.
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Rect textHeightWidth = new Rect();
pText.getTextBounds(fromWhichMode, 0, fromWhichMode.length(), textHeightWidth);
canvas.drawText(textToStamp, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
pText);
Above changes giving me text in middle of blue strip. But core ISSUE remains same. i.e Text size changes with respect to different image sizes.
Check the below code:-
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
String text = "Maulik";
Paint pText = new Paint();
pText.setColor(Color.WHITE);
setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
int x= ((newBitmap.getWidth()-(int)pText.measureText(text))/2);
int h=(extraHeight+bounds.height())/2;
int y=(originalBitmap.getHeight()+h);
canvas.drawText(text, x, y, pText);
imageView.setImageBitmap(newBitmap);
}
private void setTextSizeForWidth(Paint paint, float desiredHeight,
String text) {
// Pick a reasonably large value for the test. Larger values produce
// more accurate results, but may cause problems with hardware
// acceleration. But there are workarounds for that, too; refer to
// http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
final float testTextSize = 48f;
// Get the bounds of the text, using our testTextSize.
paint.setTextSize(testTextSize);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
// Calculate the desired size as a proportion of our testTextSize.
float desiredTextSize = testTextSize * desiredHeight / bounds.height();
// Set the paint for that size.
paint.setTextSize(desiredTextSize);
}
Edit:-
Instead of above addStampToImage method you can also use your updated addStampToImage method like below:-
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
String text = "Maulik";
Paint pText = new Paint();
pText.setColor(Color.WHITE);
setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
Rect textHeightWidth = new Rect();
pText.getTextBounds(text, 0, text.length(), textHeightWidth);
canvas.drawText(text, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
pText);
imageView.setImageBitmap(newBitmap);
}
try this one i think help to you
/**
* FOR WATER-MARK
*/
public static Bitmap waterMark(Bitmap src, String watermark, Point location, int color, int alpha, int size, boolean underline) {
int[] pixels = new int[100];
//get source image width and height
int widthSreen = src.getWidth(); // 1080L // 1920
int heightScreen = src.getHeight(); // 1343L // 2387
Bitmap result = Bitmap.createBitmap(widthSreen, heightScreen, src.getConfig());
//create canvas object
Canvas canvas = new Canvas(result);
//draw bitmap on canvas
canvas.drawBitmap(src, 0, 0, null);
//create paint object
Paint paint = new Paint();
// //apply color
// paint.setColor(color);
// //set transparency
// paint.setAlpha(alpha);
// //set text size
size = ((widthSreen * 5) / 100);
paint.setTextSize(size);
// paint.setAntiAlias(true);
// //set should be underlined or not
// paint.setUnderlineText(underline);
//
// //draw text on given location
// //canvas.drawText(watermark, w / 4, h / 2, paint);
Paint.FontMetrics fm = new Paint.FontMetrics();
paint.setColor(Color.WHITE);
// paint.setTextSize(18.0f);
paint.getFontMetrics(fm);
int margin = 5;
canvas.drawRect(50 - margin, 50 + fm.top - margin,
50 + paint.measureText(watermark) + margin, 50 + fm.bottom
+ margin, paint);
paint.setColor(Color.RED);
canvas.drawText(watermark, 50, 50, paint);
return result;
}
call this method on your onActivityResult
Bitmap bitmapp = waterMark(bitmap, your_string, p, Color.RED, 90, 90, true);

How to center image inside a circular imageview?

I have an ImageView. I have done some manipulation to make it circular. All is good. But, I realize that the image is not centered. Apparently, the image is positioned from the top left of the ImageView. How can I make this image centered to the circular ImageView?
Here is my code:
// Decode the Byte[] into bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
// Set the Bitmap into the imageView
mImage.setImageBitmap(bmp);
//circle img
int wbmp = bmp.getWidth();
int hbmp = bmp.getHeight();
int diameter;
if (wbmp > hbmp) {
diameter = hbmp;
} else {
diameter = wbmp;
}
Bitmap resized = Bitmap.createScaledBitmap(bmp, wbmp, hbmp, true);
Bitmap conv_bm = ImageHelper.getRoundedRectBitmap(resized, diameter);
mImage.setImageBitmap(conv_bm);
// TODO Auto-generated method stub
//circle img ends
and this is the ImageHelper:
public class ImageHelper {
//circle image
public static Bitmap getRoundedRectBitmap(Bitmap bitmap, int radius) {
Bitmap result = null;
try {
Bitmap sbitmap;
if(bitmap.getWidth() != radius || bitmap.getHeight() != radius) sbitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,false);
else sbitmap = bitmap;
result = Bitmap.createBitmap(sbitmap.getWidth(), sbitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
int color = 0xff424242;
Paint paint = new Paint();
Rect rect = new Rect(0, 0, sbitmap.getWidth(), sbitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(sbitmap.getWidth() / 2, sbitmap.getHeight() / 2,
sbitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
}
return result;
}
//circle image ends
}

How to add String on Bitmap Image in Android?

I want to add a string on bitmap image.I have a metod drawTextToBitmap,this method working success place string on bitmap image.But my bitmap image is very small like pinmark image.This function set the string based on the bitmap height and width.I want to place the string exceed than the bitmap image.So Please help me to solve the problem.
Following method i am using to get bitmap :
public Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
// set default bitmap config if none
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.BLACK);
// text size in pixels
paint.setTextSize((int) (70 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int m = (bitmap.getWidth() - bounds.width()) / 2;
int l = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(gText, 1000, l, paint);
return bitmap;
}
Try this:
public static Bitmap drawStringonBitmap(Bitmap src, String string, Point location, int color, int alpha, int size, boolean underline,int width ,int height) {
Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(string, location.x, location.y, paint);
return result;
}

how to draw text with background color using canvas

I have some code where I'm drawing my text on bitmap (canvas)
canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);
Please tell me, it's possible to draw this text in path(textPath) with background color?
it's full function for drawing only text
public void drawText(float x,float y ,String Text,Canvas canvas,Paint paint1 ,int count )
{
float xren =text.measureText(Text.trim());
canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);
}
Using this function I'm drawing text on my canvas. so how to modify this function for drawing this text with background?
Most likely two steps are needed here. you would draw a line along path first with color for background and then draw the text as indicated. Set the thickness of the line with a paint object. Also, changing the style of the paint can help with the effect. try FILL, STROKE or FILL_AND_STROKE for different effects.
mpaint.setStyle(Paint.Style.STROKE);
mpaint.setStrokeWidth(strokeWidth);
Added sample to draw a path(rectangle) with red color:
Paint mPaint = new Paint();
mPaint.setColor(Color.RED);
Path mPath = new Path();
RectF mRectF = new RectF(20, 20, 240, 240);
mPath.addRect(mRectF, Path.Direction.CCW);
mPaint.setStrokeWidth(20);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(mPath, mPaint);
Then draw text along same path (blue color):
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(0);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(20);
canvas.drawTextOnPath("Draw the text, with origin at (x,y), using the specified paint, along the specified path.", mPath, 0, 5, mPaint);
If you want to make like this then implement below code snippet:
/**
* PUT THIS METHOD FOR IMPLEMENT WATER-MARK IN COMMON FILE
*/
public static Bitmap waterMark(Bitmap src, String watermark) {
//get source image width and height
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
Paint.FontMetrics fm = new Paint.FontMetrics();
paint.setColor(Color.WHITE);
paint.getFontMetrics(fm);
int margin = 5;
canvas.drawRect(50 - margin, 50 + fm.top - margin,
50 + paint.measureText(watermark) + margin, 50 + fm.bottom
+ margin, paint);
paint.setColor(Color.RED);
canvas.drawText(watermark, 50, 50, paint);
return result;
}
// To Get Bitmap from URI:
private Bitmap getBitmapFromUri(String photoPath) {
Bitmap image = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
return bitmap;
}
// Save Image :
private String SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/shareImage");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
// Call like this :
Bitmap bitmap = getBitmapFromUri(attachment.get(i).getPath()); // Enter here your Image path
Bitmap bitmapp = waterMark(bitmap, "ENTER YOUR TEXT FOR WATERMARK LABEL");
String path = SaveImage(bitmapp);
Uri uri = Uri.fromFile(new File(path));
Here at last from uri you can get a new implemented watermark image.
Hope this helps you.
I believe this solution is better and more flexible than drawPath.
Use this to calculate the size of the text background:
private #NonNull Rect getTextBackgroundSize(float x, float y, #NonNull String text, #NonNull TextPaint paint) {
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
float halfTextLength = paint.measureText(text) / 2 + 5;
return new Rect((int) (x - halfTextLength), (int) (y + fontMetrics.top), (int) (x + halfTextLength), (int) (y + fontMetrics.bottom));
}
Then draw the background as a Rect:
Rect background = getTextBackgroundSize(x, y, text, textPaint);
canvas.drawRect(background, bkgPaint);
canvas.drawText(text, x, t, textPaint);
this method i created , it will give you better idea how easily you can do this
public static Drawable getTextToDrawable(final String sText, final float textSize, final int textColor, final int bgColor, final int imageSize) {
Shape shape = new Shape() {
#Override
public void draw(Canvas canvas, Paint paint) {
paint.setTextSize(spToPixel(textSize));
int ivImageSize = SUtils.dpToPx(imageSize);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(sText)); // round
int height = (int) (baseline + paint.descent());
Bitmap image = Bitmap.createBitmap(ivImageSize, (int) (ivImageSize), Bitmap.Config.ARGB_8888);
canvas.drawBitmap(image, ivImageSize, ivImageSize, paint);
paint.setColor(bgColor);
if (sText != null) {
if (sText.length() < 3) {
canvas.drawCircle(ivImageSize / 2, ivImageSize / 2, ivImageSize / 2, paint);
paint.setColor(textColor);
canvas.drawText(sText, (ivImageSize - width) / 2, (height+baseline)/2, paint);
} else {
canvas.drawRect(0, 0, ivImageSize, height, paint);
paint.setColor(textColor);
canvas.drawText(sText, (ivImageSize - width) / 2, baseline, paint);
}
}
}
};
return new ShapeDrawable(shape);
}

Categories

Resources