How to center a scaled page in PDFBox - java

I am trying to center the content of my page after scaling it by a factor X. I have tried using the Matrix.translate function but I always end up getting the wrong position, except when scaling with a factor of 0.5 (which makes totally sense to me).
My current code:
for (int i = 0; i < doc.getNumberOfPages(); i++) {
pdfBuilder.addPage(doc.getPage(i));
PDPage p = pdfBuilder.getDocument().getPage(i);
Matrix matrix = new Matrix();
float scaleFactor = 0.7f;
float pageHeight = p.getMediaBox().getHeight();
float pageWidth = p.getMediaBox().getWidth();
float translateX = pageWidth * (1 - scaleFactor);
float translateY = pageHeight * (1 - scaleFactor);
matrix.scale(scaleFactor, scaleFactor);
matrix.translate(translateX, translateY);
PDPageContentStream str = new PDPageContentStream(pdfBuilder.getDocument(), p, AppendMode.PREPEND,
false);
str.beginText();
str.transform(matrix);
str.endText();
str.close();
}
I have also tried other boxes like the cropBox and bBox but I think I am totally wrong in what I do right now. Please help me! :)
Update
I finally found a solution. The new translation values I am using now look like the following.
float translateX = (pageWidth * (1- scaleFactor)) / scaleFactor / 2;
float translateY = (pageHeight * (1- scaleFactor)) / scaleFactor / 2;

Update I finally found a solution. The new translation values I am using now look like the following.
float translateX = (pageWidth * (1- scaleFactor)) / scaleFactor / 2;
float translateY = (pageHeight * (1- scaleFactor)) / scaleFactor / 2;
First of all, it is important to note what #mkl said.
The crop box may be the box you should use instead of the media box.
The code implicitly assumes that the lower left corner of the (media/crop) box is the origin of the coordinate system. This often is the case but not always.
The code only scales the static content, not annotations.
Now the explanation of the translation (e.G. translation for the page height). PLEASE NOTE THAT I AM NOT A MATHEMATICIAN AND I JUST TRIED DIFFERENT WAYS AND THIS IS THE ONE THAT WORKED FOR ME
Firsly, we multiply the page height with the opposite of the scale factor pageHeight * (1 - scaleFactor). We need the opposite because the smaller we scale something the more it needs to move from a given position. If we use the normal scale factor here, the smaller we scale an image the less it will translate to the centre.
Now the problem is that the translation is still off. Overall it moves the scaled content in the right direction, but just not into the centre. Therefore I tried dividing the calculated factor in the step before through the half of the scale factor. We use the half here because we want the content to appear in the centre. I don't know exactly why it is precisely this value, but as I said it just worked for me!
If you know why this works, feel free to edit this answer :)

Related

Scale coordinates on radar

I'm currently developing an radar for android. (Following this tutorial: http://www.androidph.com/2009/02/app-10-beer-radar.html )
I'm getting all users within a range of 5KM around my current location from the server after that I draw in my customview like this:
float xU = (float)(userLocation.getLongitude() + getWidth() / 2 - currentLong);
float yU = (float)(getHeight() / 2 - userLocation.getLatitude() + currentLat);
canvas.drawBitmap(bmpUser,xU,yU,radarPaint);
Now my problem is, that I need to scale the the points / coordinates I draw on the radar, because all users within a distance below 5KM will be drawn like only 2-3 Pixel away from the center. How would I manage to do that?
This is one way to do it. All you need to do is to set the value of the "scale" variable to the required value;
float scale = 3.0f; //set this to any number to change the drawing scale
float xU = (float)(getWidth() / 2 + (userLocation.getLongitude() - currentLong) * scale);
float yU = (float)(getHeight() / 2 - (userLocation.getLatitude() - currentLat) * scale);
canvas.drawBitmap(bmpUser,xU,yU,radarPaint);

Java rotation of pixel array

I have tried to make an algorithm in java to rotate a 2-d pixel array(Not restricted to 90 degrees), the only problem i have with this is: the end result leaves me with dots/holes within the image.
Here is the code :
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int xp = (int) (nx + Math.cos(rotation) * (x - width / 2) + Math
.cos(rotation + Math.PI / 2) * (y - height / 2));
int yp = (int) (ny + Math.sin(rotation) * (x - width / 2) + Math
.sin(rotation + Math.PI / 2) * (y - height / 2));
int pixel = pixels[x + y * width];
Main.pixels[xp + yp * Main.WIDTH] = pixel;
}
}
'Main.pixels' is an array connected to a canvas display, this is what is displayed onto the monitor.
'pixels' and the function itself, is within a sprite class. The sprite class grabs the pixels from a '.png' image at initialization of the program.
I've tried looking at the 'Rotation Matrix' solutions. But they are too complicated for me. I have noticed that when the image gets closer to a point of 45 degrees, the image is some-what stretched ? What is going wrong? And what is the correct code; that adds the pixels to a larger scale array(E.g. Main.pixels[]).
Needs to be java! and relative to the code format above. I am not looking for complex examples, simply because i will not understand(As said above). Simple and straight to the point, is what i am looking for.
How id like the question to be answered.
Your formula is wrong because ....
Do this and the effect will be...
Simplify this...
Id recommend...
Im sorry if im asking to much, but i have looked for an answer relative to this question, that i can understand and use. But to always either be given a rotation of 90 degrees, or an example from another programming language.
You are pushing the pixels forward, and not every pixel is hit by the discretized rotation map. You can get rid of the gaps by calculating the source of each pixel instead.
Instead of
for each pixel p in the source
pixel q = rotate(p, theta)
q.setColor(p.getColor())
try
for each pixel q in the image
pixel p = rotate(q, -theta)
q.setColor(p.getColor())
This will still have visual artifacts. You can improve on this by interpolating instead of rounding the coordinates of the source pixel p to integer values.
Edit: Your rotation formulas looked odd, but they appear ok after using trig identities like cos(r+pi/2) = -sin(r) and sin(r+pi/2)=cos(r). They should not be the cause of any stretching.
To avoid holes you can:
compute the source coordinate from destination
(just reverse the computation to your current state) it is the same as Douglas Zare answer
use bilinear or better filtering
use less then single pixel step
usually 0.75 pixel is enough for covering the holes but you need to use floats instead of ints which sometimes is not possible (due to performance and or missing implementation or other reasons)
Distortion
if your image get distorted then you do not have aspect ratio correctly applied so x-pixel size is different then y-pixel size. You need to add scale to one axis so it matches the device/transforms applied. Here few hints:
Is the source image and destination image separate (not in place)? so Main.pixels and pixels are not the same thing... otherwise you are overwriting some pixels before their usage which could be another cause of distortion.
Just have realized you have cos,cos and sin,sin in rotation formula which is non standard and may be you got the angle delta wrongly signed somewhere so
Just to be sure here an example of the bullet #1. (reverse) with standard rotation formula (C++):
float c=Math.cos(-rotation);
float s=Math.sin(-rotation);
int x0=Main.width/2;
int y0=Main.height/2;
int x1= width/2;
int y1= height/2;
for (int a=0,y=0; y < Main.height; y++)
for (int x=0; x < Main.width; x++,a++)
{
// coordinate inside dst image rotation center biased
int xp=x-x0;
int yp=y-y0;
// rotate inverse
int xx=int(float(float(xp)*c-float(yp)*s));
int yy=int(float(float(xp)*s+float(yp)*c));
// coordinate inside src image
xp=xx+x1;
yp=yy+y1;
if ((xp>=0)&&(xp<width)&&(yp>=0)&&(yp<height))
Main.pixels[a]=pixels[xp + yp*width]; // copy pixel
else Main.pixels[a]=0; // out of src range pixel is black
}

Android get new coordinates after rotation

Im developing simple game. I have cca. 50 rectangles arranged in 10 columns and 5 rows. It wasn't problem to put them somehow to fit the whole screen. But when I rotate the canvas, let's say about 7° angle, the old coordinates does't fit in the new position of the coordinates. In constructor I already create and define the position of that rectangles, in onDraw method I'm drawing this rectangles (of course there are aready rotated) bud I need some method that colliding with the current rectangle. I tried to use something like this (i did rotation around the center point of the screen)
int newx = (int) ((x * Math.cos(ROTATE_ANGLE) - (y * Math.sin(ROTATE_ANGLE))) + width / 2);
int newy = (int) ((y * Math.cos(ROTATE_ANGLE) + (x * Math.sin(ROTATE_ANGLE))) + height / 2);
but it doesn't works (becuase it gives me absolute wrong new coordinates). x and y are coordinates of the touch that I'm trying to calculate new position in manner of rotation. ROTATE_ANGLE is the angle of rotation the screen.
Does anybody know how to solve this problem, I already go thorough many articles, wiki, wolframalpha categories but not luck. Maybe I just need some link to understand problem more.
Thank you
You use a rotation matrix.
Matrix mat = new Matrix(); //mat is identity
mat.postRotate(ROTATE_ANGLE); //mat is a rotation matrix of ROTATE_ANGLE degrees
float point[] = {10.0, 20.0}; //create a new float array representing the point (10, 20)
mat.mapPoints(point); //rotate the point by the requested amount
Ok, find the solution.
First it is important to convert from angle to radian
Then I personly need to negate that radian value.
That's all, this solution is correct

Properly scaling or resizing an image or sprite maintaining its original aspect ratio

I have gone through a lot of answers in this site but unfortunately nothing solves the problem I am about to describe.
I have designed an app with 800x520 in landscape mode. All assets are designed using that predefined window size. I used unit system but I think that's irrelevant here.
Now, I have a sprite/image that is 85x70 in size. I want it to scale but maintaining its original aspect ratio no matter what the window/screen size of the real device is. I have the following so far, which keeps the ratio but doesn't resize properly meaning if the device screen is bigger than my predefined window size by both width and height, it shows the sprite still small. If there's no change in height but only in width or no change in width but only in height, then that's fine. The image should not be scaled on x or y. But this snippet below doesn't do the job.
float screenW = Screen.SCREEN_WIDTH; // Predefined width 800
float screenH = Screen.SCREEN_HEIGHT; // Predefined height 520
float deviceW = Gdx.graphics.getWidth(); // Actual device width that can vary
float deviceH = Gdx.graphics.getHeight(); // Actual device height that can vary
float changeX = screenW / deviceW; // Also tried deviceW / screenW
float changeY = screenH / deviceH; // Also tried deviceH / screenH
// I tried applying the changeX and changeY above
// in sprite's scale.x and scale.y respectively but no luck
// So I tried the below to get the new size of the sprite
// with and without applying scale above..
// Tried a lot of ways but no luck
float newWidth = (Sprite.WIDTH * changeX);
float newHeight = (Sprite.HEIGHT * changeY);
I do not need any actual code as long as I have a correct algo, I'd appreciate it.
The calculation for your changeX and changeY seems backwards. If the new device has a width of 1600 for example, you would want to scale by a factor of 2. Your changeX would be 1/2.
Try something like:
float changeX = deviceW / screenW;
float changeY = deviceH / screenH;
once you have calculated these you will need to scale by the lesser of the 2 to preserve the aspect ratio.
float scale = Math.min(changeX, changeY);
Then you can calculate the new value by multiplying the original sprite values by the scale

Java-AffineTransform API:Scale an image to maximum of 300*100 pixels with?

I know to do simple scaling, but how can i scale an image to a maximum of 300*100 pixels? i searched the AffineTransform API class but couldn't find a method for this.
thx in advance
I think you would need to "back into" your scale factor by figuring what scale will get your height to 300 pixels and your width to 100.
Something like
double xScale = 100/image.getWidth();
double yScale = 300/image.getHeight();
AffineTransform transform = new AffineTransform();
transform.setToScale( xScale, yScale );
//paint code goes here
This will not scale it uniformly though. To do that you need to use the same scale for x and y. So if you are trying to ensure your image fits on a screen/display/page you would take the widest dimension's scale.
so to use the above example...
double xScale = 100/image.getWidth();
double yScale = 300/image.getHeight();
double theScale = xScale > yScale ? xScale : yScale;
AffineTransform transform = new AffineTransform();
transform.setToScale( theScale , theScale );
//paint code goes here
This is just a suggestion though, hope it helps.
Calculate the factors for the transform based on the image width/height relative to the target width/height.
Write some code and if you hit a problem, ask a specific question.

Categories

Resources