Rotating a Bitmap around a point NOT center to bitmap - java

I have a bitmap that I would like to rotate about a point on a canvas. The point I want to rotate it about is not the center of the bitmap. I am using a matrix. Here is an example of what I have.
Bitmap image = ContentManager.getInstance().getImage(imageId);
Matrix matrix = new Matrix();
matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);
matrix.postRotate(rotationDegrees);
matrix.postTranslate(x / scaleX, y / scaleY);
matrix.postScale(scaleX, scaleY);
paint.setAlpha(alpha);
canvas.drawBitmap(image, matrix, paint);
I want to manipulate this code slightly to not rotate around the bitmap's center point but a different point. To illustrate more clearly I have created this picture:
.
I have tried everything I can think of from setting
matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);
to
matrix.setTranslate(pivotPoint.x, pivotPoint.y);
and a lot of other stuff. The result is the bitmap is always way off from where I expected it. (eg. rotate it about the center of the screen 90 degrees would put the bitmap 90 degrees from where it was and consequently would be rotated.) The bitmap always seems to rotate about its center point and then ends up in a random spot on the screen.

After much messing around and find this very difficult or buggy, not sure which, found the easiest solution to this is to find the new center of the bitmap and drop the image there instead, seem more complicated but it works where plain rotation/translation wasn't.
float angle;
float radius;
Bitmap wheelSelectBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Matrix matrix = new Matrix();
Point pivotPoint = new Point();
pivotPoint.set(pivotPoint.x, pivotPoint.y)
Point newCenter = new Point();
newCenter.set((int)(pivotPoint.x + (radius * Math.cos(angle)), (int)(pivotPoint.y - (radius * Math.sin(angle)));
matrix.postTranslate(newCenter.x - (bitmap.getWidth()/2f), newCenter.y - (bitmap.getHeight()/2f));
matrix.postRotate(angle, newCenter.x, newCenter.y);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null, true);
canvas.drawBitmap(bitmap, matrix, null);
This might not be perfect but working this way solved the problem for me and stopped bitmaps flying around all over the shop. It also rotates clockwise by default unlike your diagram so just use -angle for counter-CW. Not sure what is going on here as this code definitely failed to get the desired effect for me:
matrix.postTranslate(pivotPoint.x, pivotPoint.y);
matrix.postRotate(angle);
matrix.postTranslate(radius - (bitmap.getWidth()/2f), -bitmap.getHeight()/2f);
Cant see what is wrong with logic here ? But in my case the bitmap was not visible in the view here.

When rotating an object, it will rotate around the origin (upper left corner). You'll want to first translate the bitmap so the pivot point becomes (0, 0), rotate the bitmap then translate back to it's original position.
you could try something like this:
matrix.setTranslate(-px, -py);
matrix.postRotate(rotationDegrees);
matrix.setTranslate(px, py);
// Then do other things.

Related

How to rotate an image around a point in Java

I have been looking at some similar questions but none answer exactly what I need. In the solutions I found, everyone rotated the image without moving, but what I need is for this image to rotate around the initial position, and not for it to rotate in position.
Code I was using (what I found):
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(angle), img.getWidth() / 2, img.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
img = op.filter(img, null);
g.drawImage(img, getX(), getY(), null);
I need the image to rotate in relation to the first pixel of the image.
The rotate method you’re calling passes in the anchor point as the center of the image:
https://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html#rotate(double,%20double,%20double)
Try just passing in the rotation angle itself and it should rotate around the top-left:
transform.rotate(Math.toRadians(angle));

ImageView spread out animation

I basically have an ImageView which got modified with Canvas and looks like a cirlce. (original image had the dimensions of a square (500x500))
Image what the starting position looks like:
http://imgur.com/bvXdLoP
(red is transparent and got removed with help of the Canvas method)
The animation should take aroud 1000 miliseconds and during this time step for step restore to the original picture. So in the end there should be a sqaure again.
In other words the cut off corners, which are the differnce between a square and a circle (and red marked in the image), get step for step restored in around 1000 milliseconds, with a sort of spreading looking animation.
Don't really have any clue on how to achieve this, so I can just share the Canvas method I used to cut off the corners (if it helps :X):
private Bitmap createCircleImage(Bitmap bitmap) {
Bitmap bmp;
bmp = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap,
BitmapShader.TileMode.CLAMP,
BitmapShader.TileMode.CLAMP);
float radius = bitmap.getWidth() / 2f;
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
canvas.drawCircle(bitmap.getWidth()/2,bitmap.getHeight()/2,bitmap.getHeight()/2, paint);
return bmp;
}
Appreciate any help,
thank you!
There are many ways to achieve such behavior. For example you can create custom view and override its onDraw method such as
#Override
public void onDraw(Canvas canvas) {
canvas.drawCircle(viewWidth/2, viewHeight/2, currentRadius, paint);
}
and then you can just increase the radius little by little and invalidate the view.Since view is by default will clip on its clipBounds (you can only draw inside viewidth x viewheight rectangle unless you set it otherwise) you will get the effect that you want. And then you can tweak the interpolation to achieve smoother and more natural animation.
note: a bitmap shader is attached to the paint (you already know chow to create it). I don't include it in the code, since you shouldn't initialize it inside onDraw method for performance reason.

Rotate an imageView at an angle using Seekbar

I simply want to rotate an image from min to max. But for that i have used multiple images to show Progress. Can some one suggest me a way to use a single image. which can rotate at an angle from min to max.
I know there are two possible ways to achieve it.
Using Animation Classes
Custom View
I simply want to rotate this image using SeekBar in any number of steps.
How can i achieve this?
To roate an Image
private void rotate(float degree) {
final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateAnim.setDuration(0);
rotateAnim.setFillAfter(true);
imgview.startAnimation(rotateAnim);
}
Second Approach
imageView.setRotation(angle); // but requires API >= 11
I can use Matrix
Matrix matrix = new Matrix();
imageView.setScaleType(ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivX, pivY);
imageView.setImageMatrix(matrix);
How can i set Start and end angle to SeekBar min and max respectively. Which approach is better and Whether i must put it in FrameLayout to let it rotate freely.
You can do this way :
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
For details check this out.
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
matrix.postRotate(45); //here 45 is the degree of angle to rotate
You can use a Matrix as suggested here
Matrix matrix = new Matrix();
imageView.setScaleType(ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivX, pivY);
imageView.setImageMatrix(matrix);
This would be an infinite rotation but you could spin it however you want.
This view just spins 360 degrees infinitely.
final RotateAnimation R = new RotateAnimation(0, 360, view.getWidth() / 2.0f, view.getHeight() / 2.0f);
R.setRepeatCount(Animation.INFINITE);
R.setDuration(800);
view.startAnimation(R);

Android Bitmap/Canvas offset after scale

If I have a canvas, on which I draw a Bitmap like this:
canvas.drawBitmap(bmLargeImage, srcRect, destRect, paint);
and I scale the bitmap:
canvas.scale(1.5f, 1.5f, 450, 250);
I want to get the position of the Bitmap after the scale. If the position before scale was (0, 0), after scale there is a offset and I need that offset.. how can I get it?
Thanks and sorry for the simple question, newbie here...
Ok lets try to work out the best formula for this
canvas.scale(scaleX, scaleY, pivotX, pivotY);
if (scaleX >= 1){
objectNewX = objectOldX + (objectOldX - pivotX)*(scaleX - 1);
}else{
objectNewX = objectOldX - (objectOldX - pivotX)*(1 - scaleX);
}
The same for objectNewY. The new width and height of the bitmap would of course be the multiple of the old size and scale.
I believe the cleanest Solution would be to use the underlying transformation Matrix of the Canvas you are manipulating.
In Android there is the canvas.getMatrix(Matrix cmt) method available which will yield it. The transformation matrix will transform any point in world space you throw at into screen coordinates. Just use the matrix.mapPoints(float[] points) and you will be fine.
FYI, you can easily do it the other way around too. If you want to know what screen coordinate maps to which point in world space, e.g. for tapping; the inverse matrix can be used for that. It can be obtained via the matrix.invert(Matrix out) method. Use its mapPoints() for the coordinate mapping then.
Here are the official docs:
mapPoints(), invert(), getMatrix()
If you'd like know the corners of your screen relative to your original canvas, you can use canvas.getClipBounds(). This returns a Rect with edge coordinates relative to your original canvas. For instance, if you start off with a canvas size of 320 x 480 and call
canvas.scale(2, 2, getWidth()/2, getHeight()/2);
and then
canvas.getClipBounds();
you will have a Rect (call this rect) where
rect.top == 120
rect.bottom == 360
rect.left == 80
rect.right == 240

Rotated image in ImageView

I want to show an arrow that indicates the direction towards a goal, using the orientation sensor and current GPS position. Everything works well, except that I want to rotate the arrow image in my ImageView.
The current code, which shows the arrow pointing upwards, is this:
ImageViewArrow.setImageResource(R.drawable.arrow);
What is the best solution for showing the arrow, rotated by N degrees?
I tried this, but it gave messed up graphics:
Matrix matrix = new Matrix();
matrix.postRotate(Rotation);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.arrow);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
bitmapOrg.getWidth(),bitmapOrg.getHeight(), matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
InfoArrow.setScaleType(ScaleType.CENTER);
InfoArrow.setImageDrawable(bmd);
here you can find a tutorial
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
There is a matrix parameter in the createBitmap method that can be used for resizing and rotating the image. You could try something like the following:
Matrix matrix = new Matrix();
// to rotate the image bitmap use post Rotate
matrix.postRotate(45);
Bitmap rotatedImage = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true); `

Categories

Resources