I have some sprites (Well, custom classes that implement Sprite, but whatever) that I resize. AndEngine resizes the image from the center, which makes an image placed at 0,0 no longer appear at 0,0. To fix this I applied
sprite.setScaleCenterX(0);
sprite.setScaleCenterY(0);
This places the image where I want it. However, now when I rotate the image, the image moves around (If the image were a plain square, rotating it should make no visible change). To fix this I applied
sprite.setRotationCenterX((sprite.getWidth() * sprite.getScaleX()) / 2);
sprite.setRotationCenterY((sprite.getHeight() * sprite.getScaleY()) / 2);
(For some reason, resizing a Sprite doesn't change the dimensions of the sprite, just the visual image, hence multiplying it by the scale). This, however, did not correct the problem, but merely changed where the image moved to when flipped.
Is my math off here? Wouldn't this center the rotation on the image so that the image doesn't move position? Or is there something else I'm missing?
Below is full code:
Sprite sprite = new Sprite(0, 0, singleTrackTR, getVertexBufferObjectManager());
sprite.setScale(scaleX, scaleY);
sprite.setScaleCenterX(0);
sprite.setScaleCenterY(0);
sprite.setRotationCenterX((sprite.getWidth() * sprite.getScaleX()) / 2);
sprite.setRotationCenterY((sprite.getHeight() * sprite.getScaleY()) / 2);
All your code is correct. I tried it myself, both the setProperty(x, y) and the setPropertyX/Y(a) versions.
By any chance, do you have it connected to a Body? Note that the Body also doesn't scale with a Sprite's setScale. It has its own setTransform method, which takes x and y (that you both have to divide by PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT) and a rotation value.
Related
I have an Image View which displays an image (e.g 2000x1000 pixels) and I have a coordinate (X,Y) on that image (not the image view). The canvas of my Image View is 600x800 for example. How can I convert the point (X,Y) to screen coordinate so that I can draw a path with them on the OnDraw(...) method of Image View. Any help is appreciated! Thank you.
Update: If I use matrix to draw the path between coordinates, it works but the path and objects i draw become really small. Here is the code i used.
final Matrix matrix = canvas.getMatrix();
matrix.preConcat( _view.getImageMatrix() );
matrix.preScale( 1.0f /_inSampleSize, 1.0f / _inSampleSize);
canvas.setMatrix( matrix );
//I draw the path here
Update: I add a picture to show the effect when using matrix to draw the path. I would like to have the 4 line and the 4 corner balls to be in normal size. The red color is the boundary of the Image View which holds the picture.
I think that might depend on how exactly you are displaying your image. Your ImageView (600x800) is not the same aspect ratio as your bitmap (2000x1000).
You are keeping the bitmap's aspect ratio stable as you scale it down? If so, which part (height or width) takes up the full screen and which has black (or whatever else) as padding? This will help you determine your scale factor.
scale_factor = goal_height/height1; //if height is what you are scaling by
scale_factor = goal_width/width1; //if width is what you are scaling by.
I would try:
x_goal = x1 * scale_factor;
y_goal = y1 * scale_factor;
That is, if you have a point (1333, 900) in your image, and your image takes up the full width, you would multiply both x and y by 600/2000 to get (399.9, 270). (you might want to round that decimal).
If you are NOT keeping the bitmaps aspect ratio stable (that is, you're squeezing it to fit), then you'd have a height_scale_factor and a width_scale factor. So you'd take (1333,900) and multiply x by 600/2000 and y by 800/1000 to get (399.9,720).
I'm implementing 3d card flip animation for android (api > 14) and have an issue with big screen tablets (> 2048 dpi). During problem investigation i've come to the following basic block:
Tried to just transform a view (simple ImageView) using matrix and rotateY of camera by some angle and it works ok for angle < 60 and angle > 120 (transformed and displayed) but image disappears (just not displayed) when angle is between 60 and 120. Here is the code I use:
private void applyTransform(float degree)
{
float [] values = {1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f};
float centerX = image1.getMeasuredWidth() / 2.0f;
float centerY = image1.getMeasuredHeight() / 2.0f;
Matrix m = new Matrix();
m.setValues(values);
Camera camera = new Camera();
camera.save();
camera.rotateY(degree);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-centerX, -centerY); // 1 draws fine without these 2 lines
m.postTranslate(centerX, centerY); // 2
image1.setImageMatrix(m);
}
And here is my layout XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/naponer"
android:clickable="true"
android:scaleType="matrix">
</ImageView>
</FrameLayout>
So I have the following cases:
works fine for any angle, any center point if running on small screens 800X480, 1024x720, etc...
works ok for angle < 60 and > 120 when running on big screen devices 2048x1536, 2560x1600...
works ok for any angle on any device if rotation not centered (matrix pre and post translations commented out )
fails (image disappears) when running on big screen device, rotation centered and angle is between 60 and 120 degrees.
Please tell what I'm doing wrong and advise some workaround... thank you!!!
This problem is caused by the camera distance used to calculate the transformation. While the Camera class itself doesn't say much about the subject, it is better explained in the documentation for the View.setCameraDistance() method (emphasis mine):
Sets the distance along the Z axis (orthogonal to the X/Y plane on
which views are drawn) from the camera to this view. The camera's
distance affects 3D transformations, for instance rotations around the
X and Y axis. (...)
The distance of the camera from the view plane can have an affect on
the perspective distortion of the view when it is rotated around the x
or y axis. For example, a large distance will result in a large
viewing angle, and there will not be much perspective distortion of
the view as it rotates. A short distance may cause much more
perspective distortion upon rotation, and can also result in some
drawing artifacts if the rotated view ends up partially behind the
camera (which is why the recommendation is to use a distance at
least as far as the size of the view, if the view is to be rotated.)
To be honest, I hadn't seen this particular effect (not drawing at all) before, but I suspected it could be related to this question related to perspective distortion I'd encountered in the past. :)
Therefore, the solution is to use the Camera.setLocation() method to ensure this doesn't happen.
An important distinction with the View.setCameraDistance() method is that the units are not the same, since setLocation() doesn't use pixels. While setCameraDistance() adjusts for density, setLocation() does not. Therefore, if you wanted to calculate an appropriate z-distance based on the view's dimensions, remember to adjust for density. For example:
float cameraDistance = Math.max(image1.getMeasuredHeight(), image1.getMeasuredWidth()) * 5;
float densityDpi = getResources().getDisplayMetrics().densityDpi;
camera.setLocation(0, 0, -cameraDistance / densityDpi);
Instead of using 12 lines to create rotation matrix, you could just implement this one in first line http://en.wikipedia.org/wiki/Rotation_matrix
Depending of effect you want, you might want to center image to axis you want to rotate around.
http://en.wikipedia.org/wiki/Transformation_matrix
Hmm for image disappearing, I would guess it has something to do with either memory (out of memory - although this would bring exception) or rounding problems. Maybe you could try increasing precision to double precision?
One thing that comes to mind is that cos(alpha) goes toward 0 when alpha goes toward PI/2. Other than that I don's see any correlation between angles and why it doesn't work for big images.
You need to adjust your Translate coordinates. When calculating the translation for your image you need to take image size into account too. When you perform matrix calculations you set android:scaleType="matrix" for your ImageView. This aligns your image at the top left corner by default. Then, when you apply your pre/post translation, your image may get off the bounds of your ImageView (especially if the ImageView is relatively large and your image is relatively small, like in case of beeg screen tablets).
The following translation results in the image being rotated around its center Y axis and keeps the image aligned to the top left corner:
m.preTranslate(-imageWidth/2, 0);
m.postTranslate(imageWidth/2, 0);
The following alternative results in the image being rotated around its center Y/X axises and aligns the image to the center of the ImageView:
m.preTranslate(-imageWidth/2, -imageHeight/2);
m.postTranslate(centerX, centerY);
If your image is a bitmap you can use intrinsic width/height:
Drawable drawable = image1.getDrawable();
imageHeight = drawable.getIntrinsicHeight();
imageWidth = drawable.getIntrinsicWidth();
Background
I'm drawing a custom View, which consists of an arc along which images are drawn.
A bit like this "Wheel of Fortune" screenshot, where only part of a large disc is visible and, as the user drags the view, images become visible/hidden as appropriate and are drawn at the appropriate position and angle along the disc's edge.
This works fine; I use the code below to create a large bounding box (four times the width of the view, to get a more subtle arc), which I use with Path.arcTo() to draw the visible top edge of the disc.
Because the bounding box is square, the arc drawn (if I were to draw 360°) would be circular.
// Disc dimensions (based on this View's width/height/padding)
final int radius = width * 2;
final float halfWidth = width / 2f;
final float top = mTopPadding;
// Create a large, square bounding box to draw the disc in.
// Centre horizontally; top edge of the disc == top edge of this View (+ padding)
final RectF discBounds =
new RectF(-radius + halfWidth, top, radius + halfWidth, radius * 2 + top);
// Create an arc along the circumference of the disc,
// but only where it will intersect with this View
double arcSweep = Math.toDegrees(Math.asin(halfWidth / radius)) * 2;
double startAngle = 180 + ((180 - arcSweep) / 2d);
mDiscPath.reset();
mDiscPath.arcTo(discBounds, (float) startAngle, (float) arcSweep);
// Close the shape so that we fill the rest of this View
// (the area underneath the arc) with the disc bg colour
mDiscPath.lineTo(width, height);
mDiscPath.lineTo(0, height);
I then create another Path and again call arcTo(), using the exact same bounding box so that the same arc radius is maintained.
This time the sweep angle of the arc is longer, since there may be only two or three images shown within the View at one time, but an arbitrary number of images off-screen (in my case, up to about ten).
// Create another arc, along which the images should move,
// based on the number and width of the images.
// We will later use a PathMeasure object created from
// this Path to determine where to draw each image
arcSweep = (mTotalWidth * 180) / (radius * Math.PI);
startAngle = 180 + ((180 - arcSweep) / 2d);
mImagePath.reset();
mImagePath.arcTo(discBounds, (float) startAngle, (float) arcSweep);
Problem
In onDraw(), the mDiscPath is drawn as the background (canvas.drawPath(mDiscPath, fillPaint)), and then the appropriate bitmaps are drawn based on a PathMeasure object created from mImagePath and how far the user has dragged.
However, it's noticeable that the images do not precisely follow the expected path as the disc is "rotated". This causes problems, as the images need to align accurately to the edge of the disc.
For troubleshooting, I started drawing mImagePath using canvas.drawPath(mImagePath, strokePaint)) to see why the image path didn't seem to follow the disc path.
In the screenshot below, to make the problem more obvious, the regular bitmaps are not drawn on top of the disc, and mImagePath was translated downwards by 4dp (i.e. the problem is also visible when not translated).
Here we can see three independent instances of the custom View stacked on top of one another.
But it's clear that the black line (mImagePath) does not match the radius of the top of the coloured disc (mDiscPath) in each case. i.e. The radius of the black arc appears to be large than the disc's radius.
The arcs for both Path objects were created using the same bounding box, so I would expect both arcs to have the same radius.
The line on the bottom disc seems to match up well, but the top two discs are clearly wrong.
The only real difference between the discs is the number of images displayed, and therefore the sweep angle of the image path (89°, 169°, 222° respectively for the three views).
Question
Why, if the exact same square RectF bounding box is being used to create two Path objects, why do arcs drawn from these Paths have different radii?
Am I missing something? Should I be using a different API?
Postscript
I've ensured the bounding box is correctly sized and doesn't change between creating the two paths.
The start and sweep angles look correct in all cases (i.e. the midpoint of each arc is at 270°).
Creating brand new Paths or resetting the existing Paths makes no difference.
Using the same arc sweep for both Paths does work as expected.
I've tested on various devices and orientations, with and without software rendering.
I am developing a game for Android using LibGDX. I have to objects in the game that need to be rotated. The objects are a board, and a tube. The problem that I am having is this, the tube piece consists of three pieces, the center piece, and the end pieces. The tube and the board can be stretched. Because they can be stretched the end pieces have to be separate graphics so that they do not become distorted from being stretched. I am having a really hard time figuring out how to do this properly. The position and rotation are retrieved from a Box2D body.
This is what the object looks like once constructed:
tube piece with end caps http://weaverhastings.com/tube.png
This is the end piece:
end cap for the tube http://weaverhastings.com/tube_endpiece.png
This is the piece that goes in the middle:
middle piece for the tube http://weaverhastings.com/tube_middle.png
From looking at it, it looks like the problem is the origin. As the object is stretched out, the origin for the rotation of the end pieces needs to change. But I cannot figure out how to calculate that origin correctly.
Here is the code that I am using right now:
// Right border
batch.draw(border, // AtlasRegion for the border
position.x, // The position as reported from box2d body
position.y,
25 + 150 * scale.x, // 25 is 2 x the end piece width, 150 is the width of the middle piece, it is multiplied by the scale because it can be stretched.
height/2, // This is just the height of the tube piece
border.getRegionWidth(), // the is the width of the border
height,
0.6f, // The scale of the borders is fixed
0.8f,
rotation * MathUtils.radiansToDegrees); // the rotation as retrieved from box2d body
// Left border
batch.draw(border,
position.x,
position.y,
25 - 150 * scale.x,
height/2,
border.getRegionWidth(),
height,
0.6f,
0.8f,
rotation * MathUtils.radiansToDegrees);
A video can be seen of the tube piece rotating here: http://youtu.be/RusL4Mnitds
Any help would be greatly appreciated. Thank you for reading this far.
In Libgdx the origin of rotation is relative to the objects position, eg, where you tell it to be drawn.
So for the left border you would need to say the originX would be half the width of the center piece (middlePiece.width/2) or whatever and for the right piece the originX would need to be negative this value(-middlePiece.width/2). Their positions of course would need to be at the ends of the centre piece when not rotated. The OriginY for each of them would be half the height of the Center piece. (middlePiece.height/2)
Hope this helps
I have rotated a dial around its center with the helop from the link below:
http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-a-rotating-dialer/
Now I have an icon beside the dialer and I need to rotate it around the dialer, along with the dialer in a circular path.
private void rotateLogo(float degrees){
Matrix nMatrix = new Matrix();
Bitmap peopleOrg = BitmapFactory.decodeResource(getResources(), R.drawable.peoplelogo);
float translateX = dialerWidth / 2 - dialerWidth / 2;
float translateY = dialerHeight / 2 - dialerWidth / 2;
nMatrix.preTranslate(-turntable.getWidth()/2, -turntable.getHeight()/2);
nMatrix.postRotate(degrees, translateX, translateY);
nMatrix.postTranslate(turntable.getWidth()/2, turntable.getHeight()/2);
Bitmap peopleScale = Bitmap.createBitmap(peopleOrg, 0, 0, peopleOrg.getWidth(), peopleOrg.getHeight(), nMatrix, true);
peopleLogo.setImageBitmap(peopleScale);
peopleLogo.setImageMatrix(nMatrix);
}
This just causes the image to rotate around its own center and not around the dialer's center point.
I cant find out where i am wrong :(
Updates
I basically need the logo to move in a circular path and be a clickable view.
Tried using rotateAnim but the view doesnt animate and i have trouble getting the onclick event.
Would like any help that can rotate the same using matrices
Try only rotate with peopleOrg width and height.
nMatrix.postRotate(degrees, peopleOrg.getWidth()/2, peopleOrg.getHeight()/2);
Update :
Now that you let me know that your logo should be a clickable view, merging the logo image with your dialer is not applicable. To rotate the logo view around the center of dialer you should be actually calculating the (top,left) point for your logo view and moving it around, than just rotating it.
Use sine and cosine functions to get the point on the circumference of an imaginary circle for drawing your logo view.
This post will help you with calculations : How do I calculate a point on a circle’s circumference?