This question already has answers here:
How to draw text on canvas?
(3 answers)
Closed 8 years ago.
I am writing an application that consists of a gauge view. I downloaded from here and i want to draw text inside the gauge view (that is at the center of the gauge view) how can i draw a text inside a gauge view please help me.
After my friends answers in stack overflow i did it like this but it did not works please make it work
private void drawGauge()
{
if (null != mBackground)
{
mBackground.recycle();
}
/*--For Semi circle put getHeight()/2--*/
mBackground = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
newBitmap = Bitmap.createBitmap(mBackground.getWidth(), mBackground.getHeight(), Config.ARGB_8888);
Canvas newCanvas = new Canvas(newBitmap);
final Canvas canvas = new Canvas(mBackground);
final float scale = Math.min(getWidth(), getHeight());
canvas.scale(scale, scale);
canvas.translate((scale == getHeight()) ? ((getWidth() - scale) / 2) / scale : 0,(scale == getWidth()) ? ((getHeight() - scale) / 2) / scale : 0);
Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(Color.WHITE);
paintText.setTextSize(50);
paintText.setTextAlign(Align.CENTER);
paintText.setStyle(Style.FILL);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
newCanvas.drawText(captionString, 0, rectText.height(), paintText);
//canvas.drawText("MedeQuip", 200, 500, shadowpaint);
//drawRim(canvas);
//drawFace(canvas);
For vipluv:
protected void onDraw(final Canvas canvas) {
drawBackground(canvas);
final float scale = Math.min(getWidth(), getHeight());
canvas.scale(scale, scale);
canvas.translate((scale == getHeight()) ? ((getWidth() - scale) / 2) / scale : 0, (scale == getWidth()) ? ((getHeight() - scale) / 2) / scale : 0);
if (mShowNeedle) {
drawNeedle(canvas);
}
if (mShowText) {
drawText(canvas);
}
Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
paintText.setColor(Color.WHITE);
paintText.setTextSize(150);
paintText.setTextAlign(Align.CENTER);
paintText.setStyle(Style.FILL);
Rect rectText = new Rect();
paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
canvas.drawText(captionString, rectText.width(), rectText.height(), paintText);
computeCurrentValue();
}
In the onDraw() function in their GaugeView.java file, add a canvas.drawText() just before the call to computeCurrentValue().
Use your own Paint object, and make sure you have initialized its textsize and color properties.
Related
When drawing the text though, it gets blurred and not that crisp like when using below code. The only code I've used for the text painting on image can some one help me to solve this issue
code
public static Bitmap drawMultilineTextToBitmap(Context gContext, Bitmap bitmap, String gText) {
// prepare canvas
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;
}
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
TextPaint paint = new TextPaint(Paint.LINEAR_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(Color.rgb(0, 0, 0));
paint.setFakeBoldText(true);
paint.setTextSize(10);
int textWidth = canvas.getWidth() - (int) (16 * scale);
// init StaticLayout for text
StaticLayout textLayout = new StaticLayout(gText, paint,
canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
false);
// get height of multiline text
int textHeight = textLayout.getHeight();
// get position of text's top left corner
float x = (bitmap.getWidth() - textWidth);
float y = (bitmap.getHeight() - textHeight);
// draw text to the Canvas Left
canvas.save();
//canvas.translate(x, y);
canvas.translate((canvas.getWidth() / 2) - (textLayout.getWidth() / 2), y);
textLayout.draw(canvas);
canvas.restore();
return bitmap;
}
image
I guess here:
paint.setAntiAlias(true);
should be false. And two more methods which may relate to this issue:
paint.setAntiAlias(false);
paint.setFilterBitmap(false);
paint.setDither(true);
In this Image I want text to totally be in the triangle with CYAN color.
I have created my own ImageView:
public class BookImageView extends android.support.v7.widget.AppCompatImageView {
private static final Float DISCOUNT_SIDE_SIZE = 0.33333F;
private Bitmap bitmap;
private Paint drawPaint = new Paint();
private Paint trianglePaint = new Paint();
{
trianglePaint.setColor(Constants.DISCOUNT_COLOR);
trianglePaint.setStyle(Paint.Style.FILL);
trianglePaint.setShadowLayer(10.0f, 10.0f, 10.0f, Color.parseColor("#7f000000"));
trianglePaint.setAntiAlias(true);
drawPaint.setColor(Color.BLACK);
drawPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
drawPaint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
}
// Constractors ...
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (bitmap != null) {
Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(bitmap, 0, 0, null);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
float size = bitmap.getWidth() * DISCOUNT_SIDE_SIZE;
path.lineTo(size, 0);
path.lineTo(0, size);
path.lineTo(0, 0);
path.close();
tempCanvas.drawPath(path, trianglePaint);
float scale = getResources().getDisplayMetrics().density;
drawPaint.setTextSize((int) (14 * scale));
Rect textBounds = new Rect();
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
int x = (int) (size / 2) - textBounds.width() / 2;
int y = (int) (size / 2) - textBounds.height() / 2;
tempCanvas.save();
tempCanvas.rotate(-45, x, y);
tempCanvas.drawText("50%", x, y, drawPaint);
tempCanvas.restore();
setImageDrawable(new BitmapDrawable(getContext().getResources(), tempBitmap));
}
}
#Override
public void setImageBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
invalidate();
}
}
what can I do to solve this problem ?
You can try something like this
1) Measure the width of your text
Use measureText
2) From the point you are drawing calculate the width remaining to draw
3) Now depending on the use case you can curtail the length of text or scale the text as needed
int textWidthRequired = (int) drawPaint.measureText(textToDraw);
int widthRemainingToDraw = totalWidth/2 - textDrawX;
if(textWidthRequired > widthRemainingToDraw){
//handling
}
// draw text
tempCanvas.drawText(textToDraw,textDrawX, textDrawY, drawPaint);
Depending on how high up you want the text to be, you can use properties of similar triangles to first determine the maximum width of the text. In your case, size = the triangle's base, and size = the triangle's height/altitude. Let's define two variables:
Correction: The altitude won't be equal to the base. You'd need to calculate the altitude in order to use the below solution.
float triangleBase = size; // triangle base
float triangleAltitude = size; // Calculate this.
Let's say we want the text to be halfway up the center of the triangle:
float textYHeight = triangleHeight/2;
We figure out the width of the triangle at this point by using the following formula since the sides of similar triangles are proportional:
baseOfTriangleA/baseOfTriangleB = altitudeOfTriangleA/altitudeOfTriangleB;
float triangleWidthAtTextYLocation = (textYHeight * triangleBase)/triangleAltitude;
Now that we know what the width of the triangle is at this location, we can just iterate through different text scales until the text width is less than the value triangleWidthAtTextYlocation.
float scale = getResources().getDisplayMetrics().density;
int scaleFactor = 0;
drawPaint.setTextSize((int) (scaleFactor * scale));
Rect textBounds = new Rect();
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
while(textBounds.length < triangleWidthAtTextYLocation){
// Re-measure the text until it exceeds the width
scaleFactor++;
drawPaint.setTextSize((int) (scaleFactor * scale));
drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds);
}
// Once we know the scaleFactor that puts it over the width of the triangle
// at that location, we reduce it by 1 to be just under that width:
scaleFactor = Maths.abs(scaleFactor - 1);
// final text size:
drawPaint.setTextSize((int) (scaleFactor * scale));
I'm overriding View on Android to do some custom drawing, but the rendered view has not very good quality, especially the text. I have found a couple of solutions, but none worked for me. Attaching the code here. Thank you for any help.
#Override
protected void onDraw(Canvas canvas) {
int width = canvas.getWidth();
int height = canvas.getHeight();
Point a = new Point(0, 0);
Point b = new Point(width / 2, height);
Point c = new Point(width, 0);
Path trianglePath = new Path();
trianglePath.moveTo(a.x, a.y);
trianglePath.lineTo(b.x, b.y);
trianglePath.lineTo(c.x, c.y);
trianglePath.lineTo(a.x, a.y);
Paint paint = new Paint();
paint.setStrokeWidth(1);
paint.setColor(Color.parseColor("#7A7A7A"));
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
canvas.drawPath(trianglePath, paint);
Paint textPaint = new Paint();
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(height / 6);
textPaint.setTypeface(TypefaceUtils.getTypeface(getContext(), TypefaceUtils.AVAILABLE_FONTS.ROBOTO_THIN));
String receive = getContext().getString(R.string.receive_password).split("\n")[0];
String password = getContext().getString(R.string.receive_password).split("\n")[1];
Rect receiveBounds = new Rect();
Rect passwordBounds = new Rect();
textPaint.getTextBounds(receive, 0, receive.length(), receiveBounds);
textPaint.getTextBounds(password, 0, password.length(), passwordBounds);
canvas.drawText(
receive,
(width - receiveBounds.width()) / 2,
height / 3 - receiveBounds.height() + receiveBounds.height() / 5,
textPaint);
canvas.drawText(
password,
(width - passwordBounds.width()) / 2,
height / 3 + receiveBounds.height(),
textPaint);
canvas.scale(1, 1);
}
Try setting textpaint.setAntiAlias(true);
public static Bitmap getCircularBitmapWithWhiteBorder(Bitmap bitmap,
int borderWidth) {
if (bitmap == null || bitmap.isRecycled()) {
return null;
}
final int width = bitmap.getWidth() + borderWidth;
final int height = bitmap.getHeight() + borderWidth;
Bitmap canvasBitmap = Bitmap.createBitmap(width*2, height, Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
Canvas canvas = new Canvas(canvasBitmap);
float radius = width > height ? ((float) height) / 2f : ((float) width) / 2f;
canvas.drawCircle(width / 2, height / 2, radius, paint);
paint.setShader(null);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(borderWidth);
canvas.drawCircle(width / 2, height / 2, radius - borderWidth / 2, paint);
return canvasBitmap;
}
I have circular image, i want to attach next to circular image sort of a rectangle..similar to his
this is a circle, next to it there is a rectangle attached. how can I do this?
You could draw your Rectangle more or less like this:
canvas.drawRect(width/2 + radius, height/2 - radius, width , height, paint);
just adjust the parameters for positioning it correctly if needed
I am trying to cut a circle from a square bitmap using following code
Canvas canvas=new Canvas(bitmapimg );
int circleXCoord = bitmapimg .getWidth() / 2;
int circleYCoord = bitmapimg .getHeight() / 2;
int circleRadius = bitmapimg .getWidth() / 2;
Rect rect = new Rect(circleXCoord - circleRadius, circleYCoord - circleRadius, circleXCoord + circleRadius, circleYCoord + circleRadius);
int width = rect.width();
int height = rect.height();
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLUE);
canvas.drawRect(rect, paint);
canvas.drawBitmap(bitmapimg , rect, rect, paint);
Path p = new Path();
p.addCircle(circleXCoord, circleYCoord, width / 2F, Path.Direction.CW);
canvas.clipPath(p, Region.Op.DIFFERENCE);
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
The idea is to attach a square (rectangular) bitmap to canvas and then clip a circular path. Clear out the difference between the rectangle and circle (make it transparent).
The code works fine for Android 4, but on Android 2.3.3 device, the difference area is appearing black rather that transparent.
Am I missing something here or PorterDuff.Mode.CLEAR is not supported in gingerbread? Is there a better way to cut a circle from a square in Android?
Seems like PorterDuff.Mode.Clear did not work for gingerbread
Solved the problem (cut circle from square using this code)
public Bitmap BitmapCircularCroper(Bitmap bitmapimg){
Bitmap output = Bitmap.createBitmap(bitmapimg.getWidth(),
bitmapimg.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmapimg.getWidth(),
bitmapimg.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(bitmapimg.getWidth() / 2,
bitmapimg.getHeight() / 2, bitmapimg.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmapimg, rect, rect, paint);
return output;
}
import android.graphics.PorterDuff.Mode;
import android.graphics.Bitmap.Config;
public static Bitmap getCircularBitmap(Bitmap bitmap)
{
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
For anyone that's still looking at this, this answer will cause a few issues.
1.) The canvas that you are creating in this instance will not have hardware acceleration. Even though your Paint object has anti-aliasing, the canvas will not. This will cause artifacting when you decide to paint this back to your original canvas in your onDraw() call.
2.) This takes a lot more resources. You have to create a second Bitmap (which can cause OOM), and a secondary Canvas as well as all of the different alterations you have to do.
Please check out Romain Guy's answer. You create a BitmapShader and then create a RoundRect that gives you a Circle. You just need to know the dimensions of your RectF so that it can determine the circle properly.
This means that if you know the center point (x, y) and radius, you can easily determine the RectF.
left = x - radius;
top = y - radius;
right = x + radius;
bottom = y + radius;
This also means that with this solution posted below you only have to draw to the screen once, everything else is done in the off-screen buffer.
http://www.curious-creature.com/2012/12/11/android-recipe-1-image-with-rounded-corners/
The best solution is found here:
BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0.0f, 0.0f, width, height);
// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);