I am trying to center a 256px X 256px image in LibGDX. When i run the code I'm using it renders the image in the upper right hand corner of the window. For the camera's height and width I use Gdx.graphics.getHeight(); and Gdx.graphcis.getWidth(); . I set the cameras position to the camera's width divided by the two and its height divided by two... this should put it in the middle of the screen right? when I draw the texture, I set it's position to the camera's width and height divided by two -- so it's centered..or so I think. Why doesn't the image draw in the center of the screen, is there something I'm not understanding?
Thanks!
It sounds as if your camera is ok.
If you set the textures position, you set the position of the lower left corner of that texture. It is not centered. Therefore if you set it to the coordinates of the center of the screen, its extends will cover the space to the right and the top of that point. To center it, you need to subtract half of the textures width from the x, and half of the textures height from the y coordinate. Something along these lines:
image.setPosition(Gdx.graphics.getWidth()/2 - image.getWidth()/2,
Gdx.graphics.getHeight()/2 - image.getHeight()/2);
You should draw your texture at the camera position - half the dimensions of the texture...
For example:
class PartialGame extends Game {
int w = 0;
int h = 0;
int tw = 0;
int th = 0;
OrthographicCamera camera = null;
Texture texture = null;
SpriteBatch batch = null;
public void create() {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getheight();
camera = new OrthographicCamera(w, h);
camera.position.set(w / 2, h / 2, 0); // Change the height --> h
camera.update();
texture = new Texture(Gdx.files.internal("data/texture.png"));
tw = texture.getwidth();
th = texture.getHeight();
batch = new SpriteBatch();
}
public void render() {
batch.begin();
batch.draw(texture, camera.position.x - (tw / 2), camera.position.y - (th / 2));
batch.end();
}
}
Related
I was working on a "draw with mask" app. When the user drag on the screen , it cleans part of the mask.
I implemented it through cavans and with setXfermode Clear
// Specify that painting will be with fat strokes:
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(canvas.getWidth() / 15);
// Specify that painting will clear the pixels instead of paining new ones:
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
cv.drawPath(path, drawPaint);
The problem is , how can I get the percentage of space cleaned?, it doesn't necessary to be accurate, just roughly detect when more than half of screen size is clean. Thanks for helping
What you need to do is to convert your canvas in to bitmap and count the number of black pixels in it. Using simple math you can divide the number of black pixels to the number of pixels in the canvas which will give you the percentage of black pixels.
sample taken from this post:
public float percentTransparent(Bitmap bm) { //pass the converted bitmap of canvas
final int width = bm.getWidth();
final int height = bm.getHeight();
int totalBlackPixels = 0;
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
if (bm.getPixel(x, y) == Color.BLACK) {
totalBlackPixels ++;
}
}
}
return ((float)totalBlackPixels )/(width * height); //returns the percentage of black pixel on screen
}
I'm developing an app where a lot of views can be rotated - it's something like a map of physical objects. I have to detect when 2 objects (all objects are rectangles/squares) are overlapping and if a user has performed a single/double/long tap on an object. For this reason I need to know the drawing bounds of a view.
Let's look at the example image bellow - the green rectangle is rotated 45 degrees. I need to get the coordinates of the 4 corners of the green rectangle. If I use view.getHitRect() it returns the bounding box (marked in red) of the view, which is of no use to me.
Do you know how could I get the coordinates of the edges of a view?
The only solution I could think of is to subclass a View, manually store the initial coordinates of the corners and calculate their new values on every modification to the view - translation, scale and rotation but I was wondering if there is a better method.
P.S. The app should be working on Android 2.3 but 4.0+ solutions are also welcomed.
Thanks to pskink I explored again the Matrix.mapPoints method and managed to get the proper coordinates of the corners of the rectangle.
If you are running on Android 3.0+ you can easily get the view's matrix by calling myView.getMatrix() and map the points of interest. I had to use 0,0 for the upper left corner and getWidth(),getHeight() for the bottom right corner and map these coordinates to the matrix. After that add view's X and Y values to get the real values of the corners.
Something like:
float points[] = new float[2];
points[0] = myView.getWidth();
points[1] = myView.getHeight();
myView.getViewMatrix().mapPoints(points);
Paint p = new Paint();
p.setColor(Color.RED);
//offset the point and draw it on the screen
canvas.drawCircle(center.getX() + points[0], center.getY() + points[1], 5f, p);
If you have to support lower versions of Android you can use NineOldAndroids. Then I've copied and modified one of its internal methods to get the view's matrix:
public Matrix getViewMatrix()
{
Matrix m = new Matrix();
Camera mCamera = new Camera();
final float w = this.getWidth();
final float h = this.getHeight();
final float pX = ViewHelper.getPivotX(this);
final float pY = ViewHelper.getPivotY(this);
final float rX = ViewHelper.getRotationX(this);;
final float rY = ViewHelper.getRotationY(this);
final float rZ = ViewHelper.getRotation(this);
if ((rX != 0) || (rY != 0) || (rZ != 0))
{
final Camera camera = mCamera;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = ViewHelper.getScaleX(this);
final float sY = ViewHelper.getScaleY(this);;
if ((sX != 1.0f) || (sY != 1.0f)) {
m.postScale(sX, sY);
final float sPX = -(pX / w) * ((sX * w) - w);
final float sPY = -(pY / h) * ((sY * h) - h);
m.postTranslate(sPX, sPY);
}
m.postTranslate(ViewHelper.getTranslationX(this), ViewHelper.getTranslationY(this));
return m;
}
I've put this method in an overloaded class of a view (in my case - extending TextView). From there on it's the same as in Android 3.0+ but instead of calling myView.getMatrix() you call myView.getViewMatrix().
I am developing game with libgdx and i got stuck with aspect ratio on different devices.
After a lot of thinking i figured that following is best solution for the problem:
I want to have camera always fixed to 16:9 aspect ratio and draw everything using that camera
If a device aspect is for example 4:3 i want to show only part of the view, not to strech it.
it should look something like this
blue is virtual screen(camera viewport) and red is device screen(visible area to 4:3 devices)
If for example device screen is also 16:9 full view should be visible.
Problem is i don't know how to achieve this.
I've done this for portrait screens, leaving some blank spaces at the top and bottom. As you can see in the following picture, the game stays at a 4:3 ratio and leaves whatever is leftover blank.
The content is always centered, and keeps its aspect ratio by not stretching the content unevenly. So here is some sample code Im using to achieve it.
public static final float worldW = 3;
public static final float worldH = 4;
public static OrthographicCamera camera;
...
//CALCULATING THE SCREENSIZE
float tempCalc = Gdx.graphics.getHeight() * GdxGame.worldW / Gdx.graphics.getWidth();
if(tempCalc < GdxGame.worldH){
//Adjust width
camera.viewportHeight = GdxGame.worldH;
camera.viewportWidth = Gdx.graphics.getWidth() * GdxGame.worldH / Gdx.graphics.getHeight();
worldWDiff = camera.viewportWidth - GdxGame.worldW;
}else{
//Adjust Height
camera.viewportHeight = tempCalc;
camera.viewportWidth = GdxGame.worldW;
worldHDiff = camera.viewportHeight - GdxGame.worldH;
}
camera.position.set(camera.viewportWidth/2f - worldWDiff/2f, camera.viewportHeight/2f - worldHDiff/2f, 0f);
camera.zoom = 1f;
camera.update();
I'm sure im not proposing the perfect solution, but you can play with the values on how the camera position and viewports are calculated so you can achieve the desired effect. Better than nothing I guess.
Also, Clash Of The Olympians Developers talk about how to achieve something like it and still make it look good on different devices (it is really interesting, but there is no code though): Our solution to handle multiple screen sizes in Android - Part one
The newer versions of libGDX provides a wrapper for glViewport called Viewport.
Camera camera = new OrthographicCamera();
//the viewport object will handle camera's attributes
//the aspect provided (worldWidth/worldHeight) will be kept
Viewport viewport = new FitViewport(worldWidth, worldHeight, camera);
//your resize method:
public void resize(int width, int height)
{
//notice that the method receives the entire screen size
//the last argument tells the viewport to center the camera in the screen
viewport.update(width, height, true);
}
I have written a function which works with different sizes of screen and images. The image might be zoomed and translated if it's possible.
public void transformAndDrawImage(SpriteBatch spriteBatch, Texture background, float scl, float offsetX, float offseY){
float width;
float height;
float _offsetX;
float _offsetY;
float bh2sh = 1f*background.getHeight()/Gdx.graphics.getHeight();
float bw2sw = 1f*background.getWidth()/Gdx.graphics.getWidth();
float aspectRatio = 1f*background.getHeight()/background.getWidth();
if(bh2sh>bw2sw){
width = background.getWidth() / bw2sw * scl;
height = width * aspectRatio;
}
else{
height = background.getHeight() / bh2sh * scl;
width = height / aspectRatio;
}
_offsetX = (-width+Gdx.graphics.getWidth())/2;
_offsetX += offsetX;
if(_offsetX-Gdx.graphics.getWidth()<=-width) _offsetX=-width+Gdx.graphics.getWidth();
if(_offsetX>0) _offsetX=0;
_offsetY = (-height+Gdx.graphics.getHeight())/2;
_offsetY += offseY;
if(_offsetY-Gdx.graphics.getHeight()<=-height) _offsetY=-height+Gdx.graphics.getHeight();
if(_offsetY>0) _offsetY=0;
spriteBatch.draw(background, _offsetX, _offsetY, width, height);
}
How to use it? It's easy:
#Override
public void render(float delta) {
Gdx.graphics.getGL10().glClearColor( 0.1f, 0.1f, 0.1f, 1 );
Gdx.graphics.getGL10().glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT );
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
//zoom the image by 20%
float zoom = 1.2f; //Must be not less than 1.0
//translating the image depends on a few parameters such as zooming, aspect ratio of screen and image
offsetX+=0.1f; //offset the image to the left, if it's possible
offsetY+=0.1f; //offset the image to the bottom, if it's possible
transformAndDrawImage(spriteBatch, background, zoom, offsetX, offsetY);
//draw something else...
spriteBatch.end();
}
I'm trying to calibrate an OpenGL scene onto a preview camera for an augmented reality app, but the defined OpenGL perspective and the camera preview don't seem to match.
While looking around my field of view is obviously too large (in both vertical/horizontal direction).
Q: Did I misunderstand the idea of calibrating both?
Edit: I did the following check and just can't explain the result to myself.
Using the trueVerticalFOV from below for my projection matrix, the camera preview and OpenGL match perfectly.
It seems getVerticalViewAngle() didn't return the correct value. I've measured the FOV physically also resulting in trueVerticalFOV.
New Question: Why is this so? Any suggestions?
Cam Preview size and GLSurfaceView are also 800x480, cam zoom is zero.
float horizontalFOV =
camera.getParameters().getHorizontalViewAngle(); // = 60.5
float verticalFOV =
camera.getParameters().getVerticalViewAngle(); // = 47.1
float camAspect = hFOV / vFOV; // = 1.2845...
float displayWidth =
getResources().getDisplayMetrics().widthPixels; // = 800
float displayHeight =
getResources().getDisplayMetrics().heightPixels; // = 480
float displayAspect = displayWidth / displayHeight; // = 1.666...
float trueVerticalFOV = horizontalFOV / displayAspect; // = 36.30...
/Edit
Device's camera vertical FOV:
projectionFieldOfView = camera.getParameters().getVerticalViewAngle();
GLSurfaceView's aspect ratio:
public void onSurfaceChanged(GL10 unused, int width, int height) {
...
projectionAspect = (float) width / (float) height;
...
}
OpenGL's projection matrix:
Matrix.perspectiveM(
projectionMatrix, // projection matrix array
0, // array offset
projectionFieldOfView, // FOV [deg] = 47.1 deg
projectionAspect, // aspect ratio = 1.667
projectionNearClipping, // Near clipping plane = 1
projectionFarClipping ); // Far clipping plane = 3000
I am using Canvas.drawCircle to draw a circle in Android laout.
Method gets 3 parameters - first two are position - x and y.
Is it possible to skip hardcoded position of the circle and draw it centered ?
Following code can be used to get the width and height of the screen.
int width = this.getWidth();
int height = this.getHeight();
To draw circle in the middle of screen you can call :
Canvas.drawCircle(width/2, height/2)
You can paint a circle centered to the screen like this:
Display disp = ((WindowManager)this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
canvas.drawCircle(disp.getWidth()/2, disp.getHeight()/2, radius, paint);
Assuming you are extending the View class:
int CentreX = (this.getWidth() / 2);
int CentreY = (this.getHeight() / 2);