How show text in centre of each rectangle using onDraw - java

I'm trying to create a text view (black colour) containing numbers 1 to 7 (each number on top and in the centre of each grey rectangle - just like the image I've drawn below) but I'm not sure what properties I need to add in order to achieve this. I believe the code needs to go in the loop section but I don't what code. What can be done so that a number appears centralised in each grey rectangle?
desired outcome
current outcome
public class RectangleTextView extends View {
private final Paint mBackPaint = new Paint();
private final Paint mRedPaint = new Paint();
private int mSideRectWidth = 10;
public RectangleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mBackPaint.setColor(Color.BLACK);
mRedPaint.setColor(Color.RED);
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (getWidth() == 0)
return;
//draw grey boxes
setBackgroundColor(Color.parseColor("#808080"));
int boxWidth = getWidth() / 7;
//draw black lines and/or draw text in centre of each rectangle
for (int i = 0; i < 7; i++) {
canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
canvas.drawText(?);
}
//draw text in centre of each rectangle
?
//draw left end rectangle
canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint);
//draw right end rectangle
canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint);
}
}

Use canvas.drawText(). You can do it in the same loop that you draw the black lines.
for (int i = 0; i < 7; i++) {
canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
float x = ...
float y = ...
canvas.drawText(Integer.toString(i + 1), x, y, mBlackPaint);
}
You will have to figure out the x and y value for the placement of the text. If you use paint.setTextAlign(Align.CENTER), then that simplifies the x value calculation, it's just halfway between the black lines.

Use the Paint.getTextBounds() method to get the bounding area of the text, then the exact center vertically and horizontally can be extracted from the resulting Rect object:
Paint paint = new Paint();
paint.setTextSize( textSize );
Rect bounds = new Rect();
if( text != null )
paint.getTextBounds(text, 0, text.length(), bounds);
else
bounds.set(0,0,0,0);
location.x -= bounds.exactCenterX();
location.y -= bounds.exactCenterY();

Related

Why image.getRGB(x,y) returns white at some points?

I am working on a school project with swing-Java. I am trying to draw image with drawRect(x,y,width,height) method (later I will do changes to pixels, that's why I need to draw pixels one-by-one). So, I have written this code:
private void drawImage(Graphics graphics) {
int width = image.getWidth();
int height = image.getHeight();
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
int color = image.getRGB(w, h);
graphics.setColor(new Color(color));
graphics.drawRect(w, h, 1, 1);
}
}
}
This is the result:
As you can see, some pixels are drawn with white color. But when I use this code,
graphics.drawImage(image, 0, 0, this);
Image is drawn as it should:
Why image.getRGB(x,y) returns white color at some points? What am I missing here?

Draw text on bitmap in the bottom left corner

I'm trying to draw some text on bitmap with a fixed position (Bottom left corner) no matter how bitmap size different.
Code below works but, the Text is drawn on the center of the bitmap
public Bitmap drawTextToBitmap(Context gContext,
Bitmap bitmap,
String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
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(getResources().getColor(R.color.fujiColor));
paint.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/DS-DIGI.TTF"));
paint.setTextSize((int) (14 * scale));
paint.setShadowLayer(1f, 0f, 1f, getResources().getColor(R.color.fujiShadowColor));
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width()) / 2;
int y = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(gText, x, y, paint);
return bitmap;
}
What I need is something similar to this :
Thank you.
As mentioned in the official docs, the text is drawn taking the (x,y) values as origin. Change the x,y values. Something along the following lines should work.
int horizontalSpacing = 24;
int verticalSpacing = 36;
int x = horizontalSpacing;//(bitmap.getWidth() - bounds.width()) / 2;
int y = bitmap.getHeight()-verticalSpacing;//(bitmap.getHeight() + bounds.height()) / 2;

drawRoundRect in Android not working

I want to draw a rounded rectangle with drawRoundRect method in Android.
void drawRoundRect (RectF rect, float rx, float ry, Paint paint)
I'm using Android Studio, and my testing device use Android 6.0.1, API 23
This is part of my code. It works find when I put zeros in rx and ry.
public void draw(Canvas canvas){
canvas.drawColor(Color.WHITE);
canvas.drawRoundRect(rect, 0, 0, pnt);
}
This draws a black rectangle in my screen.
But when I try to make it rounded,
public void draw(Canvas canvas){
canvas.drawColor(Color.WHITE);
canvas.drawRoundRect(rect, 10, 10, pnt);
}
It draws nothing. This only draws white background....
I tried different numbers like 100, 3, 5, 0.03f etc in rx and ry,
but any numbers bigger than 0 make drawRoundRect() not working.
Is there anything wrong with my code...?
Make sure that coordinates in RectF that is used to draw rounded rectangle are correct. That means: rect.left < rect.right and rect.top < rect.bottom.
It seems that Android 7 corrects wrong coordinates itself and draws desired rounded rectangle, but Android 6 is drawing nothing if there is problem with coordinates.
you can try this we have a little calculation but it works awesomely
private void drawRoundedRect(Canvas canvas, float left, float top, float right, float bottom) {
float radius = getHeight() / 2;
canvas.drawCircle(radius, radius, radius, mainPaint);
canvas.drawCircle(right - radius, radius, radius, mainPaint);
canvas.drawRect(left + radius, top, right - radius, bottom, mainPaint);
}
or you can check this
RectF rect = new RectF(10,10,20,20);
canvas.drawRoundRect(rect , 0, 0, mPaint);
Try this,
Bitmap bitmap = Bitmap.createBitmap(
600, // Width
300, // Height
Bitmap.Config.ARGB_8888 // Config
);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
int offset = 50;
RectF rectF = new RectF(
offset, // left
offset, // top
canvas.getWidth() - offset, // right
canvas.getHeight() - offset // bottom
);
int cornersRadius = 25;
canvas.drawRoundRect(
rectF, // rect
cornersRadius, // rx
cornersRadius, // ry
paint // Paint
);
mImageView.setImageBitmap(bitmap);
You could do this,
RectF rect = new RectF(0f, 0f, width, height);
canvas.drawRoundRect(rect , 0, 0, mPaint);

Rendering an isometric grid

I'm making a map editor for an isometric game, and I'm a bit stuck on rendering an isometric guide grid (a grid that shows where objects will be placed). That is, I need to draw lines across a Graphics object in such a way that it forms a grid with cells of variable width and height. What can I do to accomplish this?
So far I have:
//The number of cells in each direction
int nv=h/cellh;
int nh=w/cellw;
for(int i=1;i<=nv;++i){
g.drawLine(0,i*cellh,i*cellh*2,0);
}
But that just draws bottom left to upper right lines that begin on the left side.
This will work as you expect:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
int width = getWidth();
int height = getHeight();
int sizeW = 50;
int sizeH = 50;
int countW = width / sizeW;
int countH = height / sizeH;
for (int i = 0; i <= countW + countH; i++) {
g.drawLine(0, i * sizeH, i * sizeH, 0);
g.drawLine(width - i * sizeW, 0, width, i * sizeW);
}
}

Drawing an image using sub-pixel level accuracy using Graphics2D

I am currently attempting to draw images on the screen at a regular rate like in a video game.
Unfortunately, because of the rate at which the image is moving, some frames are identical because the image has not yet moved a full pixel.
Is there a way to provide float values to Graphics2D for on-screen position to draw the image, rather than int values?
Initially here is what I had done:
BufferedImage srcImage = sprite.getImage ( );
Position imagePosition = ... ; //Defined elsewhere
g.drawImage ( srcImage, (int) imagePosition.getX(), (int) imagePosition.getY() );
This of course thresholds, so the picture doesn't move between pixels, but skips from one to the next.
The next method was to set the paint color to a texture instead and draw at a specified position. Unfortunately, this produced incorrect results that showed tiling rather than correct antialiasing.
g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
BufferedImage srcImage = sprite.getImage ( );
g.setPaint ( new TexturePaint ( srcImage, new Rectangle2D.Float ( 0, 0, srcImage.getWidth ( ), srcImage.getHeight ( ) ) ) );
AffineTransform xform = new AffineTransform ( );
xform.setToIdentity ( );
xform.translate ( onScreenPos.getX ( ), onScreenPos.getY ( ) );
g.transform ( xform );
g.fillRect(0, 0, srcImage.getWidth(), srcImage.getHeight());
What should I do to achieve the desired effect of subpixel rendering of an Image in Java?
You can use a BufferedImage and AffineTransform, draw to the buffered image, then draw the buffered image to the component in the paint event.
/* overrides the paint method */
#Override
public void paint(Graphics g) {
/* clear scene buffer */
g2d.clearRect(0, 0, (int)width, (int)height);
/* draw ball image to the memory image with transformed x/y double values */
AffineTransform t = new AffineTransform();
t.translate(ball.x, ball.y); // x/y set here, ball.x/y = double, ie: 10.33
t.scale(1, 1); // scale = 1
g2d.drawImage(image, t, null);
// draw the scene (double percision image) to the ui component
g.drawImage(scene, 0, 0, this);
}
Check my full example here: http://pastebin.com/hSAkYWqM
You can composite the image yourself using sub-pixel accuracy, but it's more work on your part. Simple bilinear interpolation should work well enough for a game. Below is psuedo-C++ code for doing it.
Normally, to draw a sprite at location (a,b), you'd do something like this:
for (x = a; x < a + sprite.width; x++)
{
for (y = b; y < b + sprite.height; y++)
{
*dstPixel = alphaBlend (*dstPixel, *spritePixel);
dstPixel++;
spritePixel++;
}
dstPixel += destLineDiff; // Move to start of next destination line
spritePixel += spriteLineDiff; // Move to start of next sprite line
}
To do sub-pixel rendering, you do the same loop, but account for the sub-pixel offset like so:
float xOffset = a - floor (a);
float yOffset = b - floor (b);
for (x = floor(a), spriteX = 0; x < floor(a) + sprite.width + 1; x++, spriteX++)
{
for (y = floor(b), spriteY = 0; y < floor (b) + sprite.height + 1; y++, spriteY++)
{
spriteInterp = bilinearInterp (sprite, spriteX + xOffset, spriteY + yOffset);
*dstPixel = alphaBlend (*dstPixel, spriteInterp);
dstPixel++;
spritePixel++;
}
dstPixel += destLineDiff; // Move to start of next destination line
spritePixel += spriteLineDiff; // Move to start of next sprite line
}
The bilinearInterp() function would look something like this:
Pixel bilinearInterp (Sprite* sprite, float x, float y)
{
// Interpolate the upper row of pixels
Pixel* topPtr = sprite->dataPtr + ((floor (y) + 1) * sprite->rowBytes) + floor(x) * sizeof (Pixel);
Pixel* bottomPtr = sprite->dataPtr + (floor (y) * sprite->rowBytes) + floor (x) * sizeof (Pixel);
float xOffset = x - floor (x);
float yOffset = y - floor (y);
Pixel top = *topPtr + ((*(topPtr + 1) - *topPtr) * xOffset;
Pixel bottom = *bottomPtr + ((*(bottomPtr + 1) - *bottomPtr) * xOffset;
return bottom + (top - bottom) * yOffset;
}
This should use no additional memory, but will take additional time to render.
I successfully solved my problem after doing something like lawrencealan proposed.
Originally, I had the following code, where g is transformed to a 16:9 coordinate system before the method is called:
private void drawStar(Graphics2D g, Star s) {
double radius = s.getRadius();
double x = s.getX() - radius;
double y = s.getY() - radius;
double width = radius*2;
double height = radius*2;
try {
BufferedImage image = ImageIO.read(this.getClass().getResource("/images/star.png"));
g.drawImage(image, (int)x, (int)y, (int)width, (int)height, this);
} catch (IOException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
}
However, as noted by the questioner Kaushik Shankar, turning the double positions into integers makes the image "jump" around, and turning the double dimensions into integers makes it scale "jumpy" (why the hell does g.drawImage not accept doubles?!). What I found working for me was the following:
private void drawStar(Graphics2D g, Star s) {
AffineTransform originalTransform = g.getTransform();
double radius = s.getRadius();
double x = s.getX() - radius;
double y = s.getY() - radius;
double width = radius*2;
double height = radius*2;
try {
BufferedImage image = ImageIO.read(this.getClass().getResource("/images/star.png"));
g.translate(x, y);
g.scale(width/image.getWidth(), height/image.getHeight());
g.drawImage(image, 0, 0, this);
} catch (IOException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
g.setTransform(originalTransform);
}
Seems like a stupid way of doing it though.
Change the resolution of your image accordingly, there's no such thing as a bitmap with sub-pixel coordinates, so basically what you can do is create an in memory image larger than what you want rendered to the screen, but allows you "sub-pixel" accuracy.
When you draw to the larger image in memory, you copy and resample that into the smaller render visible to the end user.
For example: a 100x100 image and it's 50x50 resized / resampled counterpart:
See: http://en.wikipedia.org/wiki/Resampling_%28bitmap%29

Categories

Resources