I am struggling with bitmap rotations. I wish to rotate a graphic around an alternate axis but I can only ever get it to rotate around the center point no matter what I do, putting in postTranlate. preTranslate, set Translate in any order doesnt work I have also tried the postRotate(45,0,0) but it always rotates around the center.
Code below taken of internet what would I do to alter its rotation point, the code below uses the launcher icon which is square I am using a long thin graphic like an arrow.
// Rotate image to 45 degrees.
public void RotateImage(){
ImageView image;
Bitmap bMap;
Matrix matrix;
//Get ImageView from layout xml file
image = (ImageView) findViewById(R.id.imageView1);
//Decode Image using Bitmap factory.
bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//Create object of new Matrix.
matrix = new Matrix();
//set image rotation value to 45 degrees in matrix.
matrix.postRotate(45);
//Create bitmap with new values.
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
bMap.getWidth(), bMap.getHeight(), matrix, true);
//put rotated image in ImageView.
image.setImageBitmap(bMapRotate);
}
I have tried the code below but its still rotates around the center or at least appears too
public void RotateImage{
ImageView image;
Bitmap bMap;
Matrix matrix;
//Get ImageView from layout xml file
image = (ImageView) findViewById(R.id.imageView);
//Decode Image using Bitmap factory.
bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//Create object of new Matrix.
matrix = new Matrix();
//set image rotation value to 45 degrees in matrix.
matrix.setTranslate(-100,-200);
matrix.postRotate(angle);
matrix.postTranslate(100,200);
//Create bitmap with new values.
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
bMap.getWidth(), bMap.getHeight(), matrix, true);
//put rotated image in ImageView.
image.setImageBitmap(bMapRotate);
Thanks
If you want your Bitmap to rotate 45 degree around x axis with pivot (a,b), you can call matrix.rotate(45, a, b)
Perhaps you want to use the Camera class to rotate around X, Y or Z axis:
matrix = new Matrix();
Camera camera = new Camera();
camera.save();
camera.rotateX(45f);
camera.getMatrix(matrix);
camera.restore();
The way I understand your question is that you want to rotate the image around some point, say (x, y). Conceptually you need to perform the following transformations on the image:
Translate by (-x, -y)
Rotate by 45 degrees
Translate by (x, y)
You can use this method to rotate an object from center create this method in sprite class
public void paintFromCenter(float angle, Canvas c) {
Bitmap b = sprite;
Bitmap h = b;
// Canvas canvas = new Canvas(a);
Matrix matrix = new Matrix();
matrix.postRotate(angle, h.getWidth() / 2, h.getHeight());
matrix.postTranslate(getX(), getY());
// canvas.drawBitmap(bitmap, matrix, new Paint());
Bitmap bmp2 = Bitmap.createBitmap(h, 0, 0, frameWidth, frameHeight,
matrix, true);
c.drawBitmap(h, matrix, null);
// g.getCanvas().drawBitmap(bmp2, getX(), getY(), null);
}
Now in onTouchEvent()
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
evX = (int) event.getX();
evY = (int) event.getY();
int initX = objectSprite.getX();
int inity = objectSprite.getY();
if ((evX > objectSprite.getX()
&& evX < objectSprite.getX() + objectSprite.getWidth()
&& evY > objectSprite.getY() && evY < objectSprite.getY()
+ objectSprite.getHeight())) {
if (angle < 90) {
angle += 5;
} else if (angle < -180)
angle -= 5;
}
}
return true;
}
in draw() method paint the image/object
private void draw(Canvas canvas) {
objectSprite.paintFromCenter(angle, canvas);
}
try it
Related
I've got a strange problem with Bitmap rotation.
That's my code:
in onDraw method
int cx_gear_big = (getWidth() - gear_big.getWidth()) >> 1;
int cy_gears_big = (getHeight() - gear_big.getHeight()) >> 1;
canvas.drawBitmap(rotateGear(gear_big, bigGearAngle), cx_gear_big,cy_gears_big, null);
That's my method which returns rotated Bitmap:
public static Bitmap rotateGear(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
I have few gears in my canvas, but it doesn't really matter.
My problem is:
When I'm rotating my Bitmap (a gear) it moves down and left (it depends on the angle of rotation) then it comes back...
Where can my problem be in this case?
UPD:
Translation of Bitmap is not linear. It's like bouncing.
So ideal way to solve this problem is translate matrix before rotation and translate it back. Code example:
Matrix m = new Matrix();
float px = getWidth()/2;
float py = getHeight()/2;
m.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
m.postRotate(angle);
m.postTranslate(px, py);
canvas.drawBitmap(bitmap, m, null);
Just use this code
matrix.setRotate(angle, bitmap.getWidth()/2, bitmap.getHeight()/2);
hello i want to rotate image view by latitude and longitude suppose i have
lat/LNG: (33.6343541968021,73.06278146803379)
now i want my image-view(needle) point this location how i can do this?
i am doing this
public void onSensorChanged(SensorEvent event) {
float degree = Math.round(event.values[0]);
RotateAnimation ra1 = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra1.setDuration(0);
// set the animation after the end of the reservation status
ra1.setFillAfter(true);
compass_img.startAnimation(ra1);
currentDegree= -degree;}
i am using orientation sensor
Try this way
// Get the image we want to work with from a URL
Bitmap myBitmap = BitmapFactory.decodeStream(downloadImageFromWeb());
// or just load a resource from the res/drawable directory:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android1);
// find the width and height of the screen:
Display d = getWindowManager().getDefaultDisplay();
int x = d.getWidth();
int y = d.getHeight();
// get a reference to the ImageView component that will display the image:
ImageView img1 = (ImageView)findViewById(R.id.img1);
// scale it to fit the screen, x and y swapped because my image is wider than it is tall
Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, y, x, true);
// create a matrix object
Matrix matrix = new Matrix();
matrix.postRotate(-90); // anti-clockwise by 90 degrees
// create a new bitmap from the original using the matrix to transform the result
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
// display the rotated bitmap
img1.setImageBitmap(rotatedBitmap);
Check Create our Android Compass and Rotating a Bitmap in Android
I have two ImageView/Bitmap, one for visible background and it not movable one, Another one is movable bitmap on the background view. The movable bitmap have pinch zoom and rotate with matrix. Finally find movable co-ordinates/rect position and crop background bitmap using those rect position. My question is how to calculate/get rect position?.
For my sample, what i need for your view. Pleas post your idea here, it help to every one.
I spend more time to search and after few weeks for get this result.
private Bitmap getCroppedBmp(Bitmap childBmp, Bitmap ParentBmp) {
// viewBmp is movable bitmap, orgBitmap is Parent Bitmap
Bitmap viewBmp = childBmp;
Bitmap orgBitmap = ParentBmp;
float[] v = new float[9];
// get Matrix from View
cropImage.savedMatrix.getValues(v);
float left = v[Matrix.MTRANS_X];
float top = v[Matrix.MTRANS_Y];
// calculate the degree of rotation
float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X],
v[Matrix.MSCALE_X]) * (180 / Math.PI));
// Rotate viewBmp
Matrix m = new Matrix();
m.postRotate(rAngle, viewBmp.getWidth() / 2, viewBmp.getHeight() / 2);
Bitmap bmap = Bitmap.createBitmap(viewBmp, 0, 0, viewBmp.getWidth(),
viewBmp.getHeight(), m, true);
// calculate real scale
float rScale = (float) Math
.sqrt((v[Matrix.MSCALE_X] * v[Matrix.MSCALE_X])
+ (v[Matrix.MSKEW_Y] * v[Matrix.MSKEW_Y]));
// Scale viewBmp
Matrix m1 = new Matrix();
m1.postScale(rScale, rScale, width / 2, height / 2);
Bitmap scaledBitmap = Bitmap.createBitmap(bmap, 0, 0, width, height,
m1, true);
// Finally Get cropped Bitmap
Bitmap resultingImage = Bitmap.createBitmap(orgBitmap, (int) left,
(int) top, scaledBitmap.getWidth(), scaledBitmap.getHeight());
return resultingImage;
}
I want to Rotate Image according to a specific angle in android ,some thing like a compass...
I have this code...it works on drawPath()
but i want to replace the path and the Drawing thing with image..
I tried to create a bitmap image ,DrawBitmapImage , but the image does not Rotate like the path..Any Help PLease?
public void draw(Canvas canvas) {
double angle = calculateAngle(currentLongitude, currentLatitude, targetLongitude, targetLatitude);
//Correction;
angle-=90;
//Correction for azimuth
angle-=azimuth;
if((getContext() instanceof Activity) && ((Activity)getContext()).getWindowManager().getDefaultDisplay().getOrientation()==Configuration.ORIENTATION_PORTRAIT)angle-=90;
while(angle<0)angle=angle+360;
Rect rect = canvas.getClipBounds();
int height = rect.bottom-rect.top;
int width = rect.right-rect.left;
int left = rect.left;
int top = rect.top;
if(height>width){
top+=(height-width)/2;
height=width;
}
if(width>height){
left+=(width-height)/2;
width=height;
}
float centerwidth = width/2f;
float centerheight = height/2f;
Paint p = new Paint();
p.setColor(color);
p.setStyle(Paint.Style.FILL);
p.setAntiAlias(true);
float startX = left+(float)(centerwidth+Math.cos(deg2rad(angle))*width/3.0);
float startY = top+(float)(centerheight+Math.sin(deg2rad(angle))*height/3.0);
Path path = new Path();
path.moveTo(
startX,
startY);
path.lineTo(
left+(float)(centerwidth+Math.cos(deg2rad(angle+140))*width/4.0),
top+(float)(centerheight+Math.sin(deg2rad(angle+140))*height/4.0));
path.lineTo(
left+(float)centerwidth,
top+(float)centerheight
);
path.lineTo(
left+(float)(centerwidth+Math.cos(deg2rad(angle+220))*width/4.0),
top+(float)(centerheight+Math.sin(deg2rad(angle+220))*height/4.0)
);
path.lineTo(
startX,
startY
);
canvas.drawPath(path, p);
}
You can either rotate your bitmap when you draw it by using a matrix:
Matrix matrix = new Matrix();
matrix.setRotate(angle, imageCenterX, imageCenterY);
yourCanvas.drawBitmap(yourBitmap, matrix, null);
You can also do it by rotating the canvas before drawing:
yourCanvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
yourCanvas.rotate(-angle);
yourCanvas.drawBitmap(yourBitmap, left, top, null);
yourCanvas.restore();
Pick the one that suits you the best.
You have to rotate the canvas first and then draw whatever you want. Then the object drawn will be appeared as rotated on screen.
canvas.rotate(45); // degrees to rotate
try this its good way.
Check this tutorial you will get information about how to draw bitmap and how to rotate canvas
Check complete tutorial
This is the only one that worked for me with no problem.
private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngleDegree){
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int
newW=w, newH=h;
if (rotationAngleDegree==90 || rotationAngleDegree==270){
newW = h;
newH = w;
}
Bitmap rotatedBitmap = Bitmap.createBitmap(newW,newH, bitmap.getConfig());
Canvas canvas = new Canvas(rotatedBitmap);
Rect rect = new Rect(0,0,newW, newH);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotationAngleDegree);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ));
matrix.reset();
return rotatedBitmap;
}
Based on #Sakthi 's code, but add scaling :)
Rect rect = new Rect(0,0,canvas.getWidth(), canvas.getHeight());
Matrix matrix = new Matrix();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postScale(
((float)rect.width()) / bitmap.getWidth(),
((float)rect.height()) / bitmap.getHeight());
matrix.postRotate(180);
matrix.postTranslate(rect.exactCenterX(), rect.exactCenterY());
canvas.drawBitmap(bitmap, matrix, null);
#Reham: Look at this example code below,
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// 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);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
you have to use the matrix to rotate image look the lines
matrix.postRotate(45); -
this will rotate the image to 45 degrees
Hope this help you ...thx
Use following code. it worked for me
float rotation = 30.0f;
Bitmap bitmap = your bitmap
Rect rect = new Rect(100,100,bitmap.width, bitmap.height);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotation);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, null);
matrix.reset();
invalidate();
I am trying to rotate a bitmap image 90 degrees to change it from a landscape format to a portrait format. Example:
[a, b, c, d]
[e, f, g, h]
[i, j, k, l]
rotated 90 degree clockwise becomes
[i,e,a]
[j,f,b]
[k,g,c]
[l,h,d]
Using the code below (from an online example) the image is rotated 90 degrees but retains the landscape aspect ratio so you end up with a vertically squashed image. Am I doing something wrong? Is there another method I need to use? I am also willing to rotate the jpeg file that I'm using to create the bitmap if that is easier.
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(90);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOriginal, 0, 0, widthOriginal, heightOriginal, matrix, true);
This is all you need to rotate the image:
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(original, 0, 0,
original.getWidth(), original.getHeight(),
matrix, true);
In your code sample, you included a call to postScale. Could that be the reason your image is being stretched? Perhaps take that one out and do some more testing.
Here's how you would rotate it properly (this insures proper rotation of the image)
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(
b, 0, 0, b.getWidth(), b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {
throw ex;
}
}
return b;
}
This code worked great for me:
Matrix matrix = new Matrix();
matrix.setRotate(90, 0, 0);
matrix.postTranslate(original.getHeight(), 0);
rotatedBitmap = Bitmap.createBitmap(newWidth, newHeight, original.getConfig());
Canvas tmpCanvas = new Canvas(rotatedBitmap);
tmpCanvas.drawBitmap(original, matrix, null);
tmpCanvas.setBitmap(null);
check the canvas size where you draw the bitmap, maybe your canvas is still landscape, so only the square part of the rotated bitmap could be seen.