Android - Draw Bitmap within Canvas - java

I currently have a maze game which draws a 5 x 5 square (takes the width of screen and splits it evenly). Then for each of these boxes using x and y cordinates I user drawRect, to draw a colored background.
The issue I am having is I now need to draw an image within this same location, therefore replacing the current plain background colour fill.
Here is the code I am currently using to drawRect (a few example):
// these are all the variation of drawRect that I use
canvas.drawRect(x, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x + 1, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x, y + 1, (x + totalCellWidth), (y + totalCellHeight), green);
I would then also need to implement a background image for all the other squares within my canvas. This background will have simple 1px black lines drawn over the top of it, current code to draw in a grey background.
background = new Paint();
background.setColor(bgColor);
canvas.drawRect(0, 0, width, height, background);
Could you please advice if this is at all possible. If so, what is the best way I can go about doing this, whilst trying to minimise memory usage and having 1 image which will expand and shrink to fill the relvent square space(this varies on all the different screen sizes as it splits the overall screen width evenly).

Use the Canvas method public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint). Set dst to the size of the rectangle you want the entire image to be scaled into.
EDIT:
Here's a possible implementation for drawing the bitmaps in squares across on the canvas. Assumes the bitmaps are in a 2-dimensional array (e.g., Bitmap bitmapArray[][];) and that the canvas is square so the square bitmap aspect ratio is not distorted.
private static final int NUMBER_OF_VERTICAL_SQUARES = 5;
private static final int NUMBER_OF_HORIZONTAL_SQUARES = 5;
...
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int squareWidth = canvasWidth / NUMBER_OF_HORIZONTAL_SQUARES;
int squareHeight = canvasHeight / NUMBER_OF_VERTICAL_SQUARES;
Rect destinationRect = new Rect();
int xOffset;
int yOffset;
// Set the destination rectangle size
destinationRect.set(0, 0, squareWidth, squareHeight);
for (int horizontalPosition = 0; horizontalPosition < NUMBER_OF_HORIZONTAL_SQUARES; horizontalPosition++){
xOffset = horizontalPosition * squareWidth;
for (int verticalPosition = 0; verticalPosition < NUMBER_OF_VERTICAL_SQUARES; verticalPosition++){
yOffset = verticalPosition * squareHeight;
// Set the destination rectangle offset for the canvas origin
destinationRect.offsetTo(xOffset, yOffset);
// Draw the bitmap into the destination rectangle on the canvas
canvas.drawBitmap(bitmapArray[horizontalPosition][verticalPosition], null, destinationRect, null);
}
}

Try the following code :
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawBitmap(bitmap, x, y, paint);
==================
You could also just reference this answer.

Related

Unexpected circle border drawn with AWT

With AWT I draw a border using java.awt.Graphics#drawOval and java.awt.Graphics2D#setStroke. For situations when the set stroke has a size bigger than the oval's diameter the resulting border is not like expected. In that situation the stroke overlaps the stroke of the other side of the circle: Circles north stroke overlaps the south stroke. AWT renders this overlapping in an XOR way as you can see in the following image.
What I'd expect instead is that the stroke overlapping is drawn in an OR way, so that in all situations when stroke width > circle diameter the center is black.
Is there a simple way I can set to change the behaviour to an OR overlapping mode, even when width or height of the circle (then its an ellipse) is not equal?
Same diameter (10px) with increasing stroke width:
Based on the solution that Marco13 mentioned in his comment I came up with this custom drawOval function. It basically switch from drawOval to fillOval once the stroke width is greater than the diameter. The position and dimensions for the fillOval function are calculated to match the drawOval output.
public static void drawOval(Graphics2D g2d, int strokeWidth, int x, int y, int width, int height) {
int minLength = Math.min(width, height);
int maxLength = Math.max(width, height);
if (minLength >= strokeWidth) {
g2d.drawOval(x, y, width, height);
} else {
int x1 = x - (strokeWidth - maxLength) / 2 - (maxLength / 2);
int y1 = y - (strokeWidth - maxLength) / 2 - (maxLength / 2);
int width1 = width + strokeWidth;
int height1 = height + strokeWidth;
g2d.fillOval(x1, y1, width1, height1);
}
}
This is how it looks like

draw curves lines android

I drew 4 lines from the center towards the button as I show you in the photo. I do not know how I can draw curved lines that are in red color in the picture.
[enter image description here]
or
[enter image description here (simpler)]
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int x = metrics.widthPixels;
int y = metrics.heightPixels;
Paint paint1 = new Paint () ;
paint1.setStrokeWidth(10);
int margin = 100;
int margin1 = 300;
int top = 0 + margin;
int bottom = canvas.getHeight() - margin;
int left = 0 + margin1;
int right = canvas.getWidth() - margin1;
int centerX = x / 2;
int centerY = y / 2;
canvas.drawLine(centerX, top, centerX, bottom,paint1);
canvas.drawLine(left, centerY, right, centerY,paint1);
You will need to split it in 4 different parts (curves) for easier drawing
Here is my sketch(sorry for quick drawing)
So you need to get 4 points for bezieres and should be something like this
1st move to start (drawing point)
path.moveTo(x1, y1);
then use next for draw path
cubicTo(x2, y2, x3, y3, x4,y4)
and finally
canvas.drawPath(path, paint);
Same procedure make for rest 3 quadrant/parts
hope this will help you to archive your goal

Kaleidoscope Effect in Android

I'm trying to create a Kaleidoscope with an ImageView in Android. I'm struggling to get the rotation and mirroring for each 'segment' correct. I'm new to image manipulation and I'm trying to adapt the code example from here for android.
I have the following code:
private void drawKaleidoscope() {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.cropped_landscape);
Bitmap imageview_bitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap matrix_bitmap;
BitmapShader fillShader;
Path triangle_mask = new Path();
RectF r = new RectF(0, 0, bm.getWidth(), bm.getHeight()); // create new rectangle to match the dimensions of our image
this.radius = (int)r.height() / 2;
Canvas c = new Canvas(imageview_bitmap);
c.drawColor(Color.BLACK);
float start_angle = 0;
for (int i = 0; i < this.segments; i++) {
// Create pie-slice shape mask
triangle_mask.reset();
triangle_mask.moveTo(r.centerX(), r.centerY());
triangle_mask.arcTo(r, start_angle, angle);
triangle_mask.close();
// Use odd even check to decide when to mirror the image or not
if (i % 2 == 0) {
Matrix mat = new Matrix();
mat.preTranslate(-radius, -radius);
mat.postRotate(i * angle);
mat.postTranslate(radius, radius);
matrix_bitmap = Bitmap.createBitmap(bm, 0, 0, (int)r.width(), (int)r.height(), mat, true);
}
else {
Matrix mat = new Matrix();
// mirror on x axis
mat.postScale(-1, 1);
mat.postTranslate(-radius, radius);
mat.postRotate((float)-Math.PI);
mat.postRotate(i * angle);
mat.postTranslate(radius, -radius);
matrix_bitmap = Bitmap.createBitmap(bm, 0, 0, (int)r.width(), (int)r.height(), mat, true);
}
fillShader = new BitmapShader(matrix_bitmap, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
// Fill the triangle masked area with our image now
Paint fill = new Paint();
fill.setColor(0xFFFFFFFF);
fill.setStyle(Paint.Style.FILL);
fill.setShader(fillShader);
c.drawPath(triangle_mask, fill);
start_angle += angle;
}
kal.setImageBitmap(imageview_bitmap);
}
The output of the above function looks like so:
If anyone could provide some insight on how to properly do the image rotations/mirroring that would be greatly appreciated.
Okay I ended up going about this a different way. Instead of rotating the source image I simply draw the image mask to the same spot on the canvas, and then rotate the canvas itself. Let's say I have 12 image 'slices'. I draw 6 alternating segments, flip the canvas via canvas.scale(-1, 1) and then draw another 6 segments in where the blank spaces are. Here's the code I ended up with:
private Bitmap generateKaleidoscopeBitmap(float start_angle) {
Canvas canvas = new Canvas(imageview_bitmap);
canvas.drawColor(Color.BLACK);
BitmapShader fillShader;
Path triangle_mask = new Path();
RectF r = new RectF(0, 0, imageview_bitmap.getWidth(), imageview_bitmap.getHeight()); // create new rectangle to match the dimensions of our image
int centerX = imageview_bitmap.getWidth() / 2;
int centerY = imageview_bitmap.getHeight() / 2;
// how much to rotate the canvas by after the image is flipped
float offset = calculateCanvasSymmetryOffset(start_angle);
// Create a pie-slice shaped clipping mask
triangle_mask.moveTo(r.centerX(), r.centerY());
triangle_mask.arcTo(r, start_angle, angle);
triangle_mask.close();
// Fill the triangle masked area with our shader now
Paint fill = new Paint();
fill.setColor(0xFFFFFFFF);
fill.setStyle(Paint.Style.FILL);
fillShader = new BitmapShader(source_image, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
fill.setShader(fillShader);
// Rotate the canvas and draw the clipping mask to the canvas
for (int i = 0; i < this.segments / 2; i++) {
canvas.drawPath(triangle_mask, fill);
canvas.rotate(angle * 2, centerX, centerY);
}
// mirror the canvas and rotate it once to counter the symmetrical offset
canvas.scale(-1, 1, centerX, centerY);
canvas.rotate(offset, centerX, centerY);
// Rotate the now mirrored canvas and draw the clipping mask to it
// This is a cheap and easy way of creating mirrored segments
for (int i = 0; i < this.segments / 2; i++) {
canvas.drawPath(triangle_mask, fill);
canvas.rotate(angle * 2, centerX, centerY);
}
return imageview_bitmap;
}

Android: Canvas scaling in different coordinate system

I'm kinda desperate already =)...
I'am drawing points and lines onto a canvas in Android. The points I'm displaying should be displayed in a mathematical system. So I did canvas.getHeight() - point.y to display the points in the right way.
But if I would like to zoom into the drawn object the y coordinate gets scaled out of my view.
That's because x = 10 and y = 700. If I scale it with a scale factor of 10, the y make the object disappear.
I hope you get what I'm talking about...
How do I display my coordinates in the right (mathematical) way without moving the y coordinate far away??
Here is what I do:
canvas.drawPoint(startPoints[i][0], height-startPoints[i][1], pointColor);
canvas.drawPoint(endPoints[i][0], height-endPoints[i][1], pointColor);
Then my point (x=10, y=10) is going to be displayed as x=10 , y = 714.
Here's my full routine
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
final float[][] startPoints;
final float[][] endPoints;
int count = 0;
height = canvas.getHeight();
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
canvas.translate(translateX / scaleFactor, translateY / scaleFactor);
Paint lineColor = new Paint();
lineColor.setColor(Color.BLACK);
Paint pointColor = new Paint();
pointColor.setColor(Color.RED);
pointColor.setStrokeWidth(5f);
startPoints = data.getStartPoints();
endPoints = data.getEndPoints();
count = data.getSize();
for (int i = 0; i < count; i++) {
canvas.drawLine(startPoints[i][0], height-startPoints[i][1],
endPoints[i][0], height-endPoints[i][1], lineColor);
canvas.drawPoint(startPoints[i][0], height-startPoints[i][1], pointColor);
canvas.drawPoint(endPoints[i][0], height-endPoints[i][1], pointColor);
}
canvas.restore();
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
return true;
}
}
scaling factor x = screen width in pixels / target width in pixels
scaling factor y = screen height in pixels / target height in pixels
or
scaled x point = x on resized canvas * (resized width / original width)
scaled y point = y on resized canvas * (resized height / original height)

How to align rectangle to bottom of any device?

rec.set(0, 0, canvas.getWidth(), canvas.getHeight()/2);
It creates the rectangle as expected, I know 0, 0 is x, y but how do I set y to the bottom so it stays at the bottom on all devices with different size?
you haven't given much information, so I'll state my assumptions
the x,y would be the top-left of your shape, so assuming that the canvas is the full height of the device:
x - 0, as you want the shape to start on the left edge, y - the height of the device minus the height of the shape
your code would be
int width = canvas.getWidth();
int height = canvas.getHeight()/2;
int x = 0;
int y = canvas.getHeight() - height;
rec.set(x, y, width, height);

Categories