Related
I'm having trouble setting the coordinate of the star are there any better solution for this. I cannot get the the correct shape. Can someone help me on this?
public void star(Graphics shapes)
{
shapes.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int [] y = {38,62,68,80,105,85,102,75,58,20,38};
shapes.fillPolygon(x, y, 5);
}
Sun's implementation provides some custom Java 2D shapes like Rectangle, Oval, Polygon etc. but it's not enough. There are GUIs which require more custom shapes like Regular Polygon, Star and Regular polygon with rounded corners. The project provides some more shapes often used. All the classes implements Shape interface which allows user to use all the usual methods of Graphics2D like fill(), draw(), and create own shapes by combining them.
Regular Polygon Star
Edit:
Link
Honestly, I'd use the 2D Graphics shapes API, they allow you to "draw" a shape, which is simpler (IMHO) then using polygon. The advantage is, they are easy to paint and transform
Having said that, the problem you're actually having is the fact that you're not passing the right information to the fillPolygon method.
If you take a look at the JavaDocs for Graphics#fillPolygon, you'll note that the last parameter is the number of points:
nPoints - a the total number of points.
But you're passing 5, where there are actually 11 points in your array
Something like...
shapes.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int [] y = {38,62,68,80,105,85,102,75,58,20,38};
shapes.fillPolygon(x, y, 11);
should now draw all the points, but some of your coordinates are slightly off, so you might want to check that
The second to last number of your Y should be 60 not 20
g2.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int[] y = {38,62,68,80,105,85,102,75,58,60,38};
g2.fillPolygon(x , y, 11);
I'm having trouble setting the coordinate of the star are there any better solution for this
Check out Playing With Shapes. You should be able to use the ShapeUtils class to generate your shape.
This class will generate the points for you so you don't need to manage every pixel.
a star has 10 points ppl mind that not 11
setBackground(Color.black);
int[]x={250,150,0,150,100,250,400,350,500,350};
int[]y={100,200,200,300,400,300,400,300,200,200};
g.fillPolygon( (x),(y),10);
setForeground(Color.cyan);
this will help to draw a star with black bg and cyan foreground
I have two numbers one above the other, but the first one must have an Strikethrough, I'm using a table and cell to put both numbers in the table, is there a way to make what I need?
Create a font with the style STRIKETHRU.
Font f = new Font(Font.FontFamily.HELVETICA, 12, Font.STRIKETHRU);
I am adding an extra answer for the sake of completeness.
Please take a look at the SimpleTable6 example:
In the first row, we strike through a number using a STRIKETHRU font as explained by Paulo:
Font font = new Font(FontFamily.HELVETICA, 12f, Font.STRIKETHRU);
table.addCell(new Phrase("0123456789", font));
In this case, iText has made a couple of decisions for you: where do I put the line? How thick is the line?
If you want to make these decisions yourself, you can use the setUnderline() method:
chunk1.setUnderline(1.5f, -1);
table.addCell(new Phrase(chunk1));
Chunk chunk2 = new Chunk("0123456789");
chunk2.setUnderline(1.5f, 3.5f);
table.addCell(new Phrase(chunk2));
If you pass a negative value for the y-offset parameter, the Chunk will be underlined (see first column). You can also use this method to strike through text by passing a positive y-offset.
As you can see, we also defined the thickness of the line (1.5f). There is another setUnderline() method that also allows you to pass the following parameters:
color - the color of the line or null to follow the text color
thickness - the absolute thickness of the line
thicknessMul - the thickness multiplication factor with the font size
yPosition - the absolute y position relative to the baseline
yPositionMul - the position multiplication factor with the font size
cap - the end line cap. Allowed values are PdfContentByte.LINE_CAP_BUTT, PdfContentByte.LINE_CAP_ROUND and PdfContentByte.LINE_CAP_PROJECTING_SQUARE
See http://api.itextpdf.com/itext/com/itextpdf/text/Chunk.html
I need to read a plan exported by AutoCAD to PDF and place some markers with text on it with PDFBox.
Everything works fine, except the calculation of the width of the text, which is written next to the markers.
I skimmed through the whole PDF specification and read in detail the parts, which deal with the graphic and the text, but to no avail. As far as I understand, the glyph coordinate space is set up in a 1/1000 of the user coordinate space. Hence the width need to be scale up by 1000, but it's still a fraction of the real width.
This is what I am doing to position the text:
float textWidth = font.getStringWidth(marker.id) * 0.043f;
contentStream.beginText();
contentStream.setTextScaling(1, 1, 0, 0);
contentStream.moveTextPositionByAmount(
marker.endX + marker.getXTextOffset(textWidth, fontPadding),
marker.endY + marker.getYTextOffset(fontSize, fontPadding));
contentStream.drawString(marker.id);
contentStream.endText();
The * 0.043f works as an approximation for one document, but fails for the next.
Do I need to reset any other transformation matrix except the text matrix?
EDIT: A full idea example project is on github with tests and example pdfs: https://github.com/ascheucher/pdf-stamp-prototype
Thanks for your help!
Unfortunately the question and comments merely include (by running the sample project) the actual result for two source documents and the description
The annotating text should be center aligned on the top and bottom marker, aligned to the left on the right marker and aligned to the right on the left marker. The alignment is not working for me, as the font.getSTringWidth( .. ) returns only a fraction of what it seems to be. And the discrepance seems to be different in both PDFs.
but not a concrete sample discrepancy to repair.
There are several issues in the code, though, which may lead to such observations (and other ones, too!). Fixing them should be done first; this may already resolve the issues observed by the OP.
Which box to take
The code of the OP derives several values from the media box:
PDRectangle pageSize = page.findMediaBox();
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
float lineWidth = Math.max(pageWidth, pageHeight) / 1000;
float markerRadius = lineWidth * 10;
float fontSize = Math.min(pageWidth, pageHeight) / 20;
float fontPadding = Math.max(pageWidth, pageHeight) / 100;
These seem to be chosen to be optically pleasing in relation to the page size. But the media box is not, in general, the final displayed or printed page size, the crop box is. Thus, it should be
PDRectangle pageSize = page.findCropBox();
(Actually the trim box, the intended dimensions of the finished page after trimming, might even be more apropos; the trim box defaults to the crop box. For details read here.)
This is not relevant for the given sample documents as they do not contain explicit crop box definitions, so the crop box defaults to the media box. It might be relevant for other documents, though, e.g. those the OP could not include.
Which PDPageContentStream constructor to use
The code of the OP adds a content stream to the page at hand using this constructor:
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
This constructor appends (first true) and compresses (second true) but unfortunately it continues in the graphics state left behind by the pre-existing content.
Details of the graphics state of importance for the observations at hand:
Transformation matrix - it may have been changed to scale (or rotate, skew, move ...) any new content added
Character spacing - it may have been changed to put any new characters added nearer to or farther from each other
Word spacing - it may have been changed to put any new words added nearer to or farther from each other
Horizontal scaling - it may have been changed to scale any new characters added
Text rise - it may have been changed to displace any new characters added vertically
Thus, a constructor should be chosen which also resets the graphics state:
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true, true);
The third true tells PDFBox to reset the graphics state, i.e. to surround the former content with a save-state/restore-state operator pair.
This is relevant for the given sample documents, at least the transformation matrix is changed.
Setting and using the CalRGB color space
The OP's code sets the stroking and non-stroking color spaces to a calibrated color space:
contentStream.setStrokingColorSpace(new PDCalRGB());
contentStream.setNonStrokingColorSpace(new PDCalRGB());
Unfortunately new PDCalRGB() does not create a valid CalRGB color space object, its required WhitePoint value is missing. Thus, before selecting a calibrated color space, initialize it properly.
Thereafter the OP's code sets the colors using
contentStream.setStrokingColor(marker.color.r, marker.color.g, marker.color.b);
contentStream.setNonStrokingColor(marker.color.r, marker.color.g, marker.color.b);
These (int, int, int) overloads unfortunately use the RG and rg operators implicitly selecting the DeviceRGB color space. To not overwrite the current color space, use the (float[]) overloads with normalized (0..1) values instead.
While this is not relevant for the observed issue, it causes error messages by PDF viewers.
Calculating the width of a drawn string
The OP's code calculates the width of a drawn string using
float textWidth = font.getStringWidth(marker.id) * 0.043f;
and the OP is surprised
The * 0.043f works as an approximation for one document, but fails for the next.
There are two factors building this "magic" number:
As the OP has remarked the glyph coordinate space is set up in a 1/1000 of the user coordinate space and that number is in glyph space, thus a factor of 0.001.
As the OP has ignored he wants the width for the string using the font size he selected. But the font object has no knowledge of the current font size and returns the width for a font size of 1. As the OP selects the font size dynamically as Math.min(pageWidth, pageHeight) / 20, this factor varies. In case of the two given sample documents about 42 but probably totally different in other documents.
Positioning text
The OP's code positions the text like this starting from identity text matrices:
contentStream.moveTextPositionByAmount(
marker.endX + marker.getXTextOffset(textWidth, fontPadding),
marker.endY + marker.getYTextOffset(fontSize, fontPadding));
using methods getXTextOffset and getYTextOffset:
public float getXTextOffset(float textWidth, float fontPadding) {
if (getLocation() == Location.TOP)
return (textWidth / 2 + fontPadding) * -1;
else if (getLocation() == Location.BOTTOM)
return (textWidth / 2 + fontPadding) * -1;
else if (getLocation() == Location.RIGHT)
return 0 + fontPadding;
else
return (textWidth + fontPadding) * -1;
}
public float getYTextOffset(float fontSize, float fontPadding) {
if (getLocation() == Location.TOP)
return 0 + fontPadding;
else if (getLocation() == Location.BOTTOM)
return (fontSize + fontPadding) * -1f;
else
return fontSize / 2 * -1;
}
In case of getXTextOffset I doubt that adding fontPadding for Location.TOP and Location.BOTTOM makes sense, especially in the light of the OP's desire
The annotating text should be center aligned on the top and bottom marker
For the text to be centered it should not be shifted off-center.
The case of getYTextOffset is more difficult. The OP's code is built upon two misunderstandings: It assumes
that the text position selected by moveTextPositionByAmount is the lower left, and
that the font size is the character height.
Actually the text position is positioned on the base line, the glyph origin of the next drawn glyph will be positioned there, e.g.
Thus, the y positioned either has to be corrected to take the descent into account (for centering on the whole glyph height) or only use the ascent (for centering on the above-baseline glyph height).
And a font size does not denote the actual character height but is arranged so that the nominal height of tightly spaced lines of text is 1 unit for font size 1. "Tightly spaced" implies that some small amount of additional inter-line space is contained in the font size.
In essence for centering vertically one has to decide what to center on, whole height or above-baseline height, first letter only, whole label, or all font glyphs. PDFBox does not readily supply the necessary information for all cases but methods like PDFont.getFontBoundingBox() should help.
I searched through the API for SpriteSheet, but I couldn't find anything on how to make a sprite sheet with different sized sprites.
The sprite sheet that I'm using has a row of 16x16px tiles, a row of 24x24px tiles under it, a row of 8x8px under that, and so on.
Originally, not using Slick2D, I used BufferedImage.getSubimage() to obtain each sprite from a temporary BufferedImage of the sprite sheet. Is there a similar method here that I can use?
I don't believe there is a way to do a direct sub-image in the current version of the API, at least at the time of this writing.
However, there are three possible options that I can think of (in addition to the option of just adding said method calls yourself - it's open source after all):
You could instantiate several SpriteSheet objects from the same source Image, one for each Sprite size, if you really want to keep them in the same source file.
You could take the Image instance, and call getSubImage on it to split the Image into three images, one for each size (24x24, 16x16, and so on). Then, from those sub-images, instantiate SpriteSheets.
You could split the source file into separate files based on the size. That is, have your 24x24 sprite cells in one file, your 16x16 in another file, and so on.
You can just keep an Image and use an overload of the Graphics object's drawImage method to specify where to draw which part of the image:
g.drawImage(image, x1, y1, x2, y2, srcX1, srcY1, srcX2, srcY2);
See [javadoc](http://slick.cokeandcode.com/javadoc/org/newdawn/slick/Graphics.html#drawImage(org.newdawn.slick.Image, float, float, float, float, float, float, float, float))
The first parameter is the instance of the image. The next two parameter define the point on screen, where the rendering begins. X2 and y2 define the end point of the rendering. Usually x2 is x1 + spriteWidth and y2 is y1 + spriteHeight, but you can change those values to draw the sprite in different sizes.
The last four parameters work the same, but they define the area of the sprite sheet, that will be drawn on screen.
If we take your example and we want to draw the second tile from the third row the call would look like this:
int tileWidth = 8;
int tileHeight = 8;
int sourceX = 40;
int sourceY = 8; //as its the sec
int drawX = 34;
int drawY = 65;
g.drawImage(image, drawX, drawY, drawX + tileWidth, drawY + tileHeight
, sourceX, sourceY, sourceX + tileWidth, sourceY + tileHeight);
When I work with spritesheet, I have hardcoded values in some (very rare cases, mostly tests) and a sprite class, that has the source x1, x2, y1 and y2 values stored. I can pack a bunch of them in a list or a map and like that I have a sprite index. Usually I generate the definitions somehow and then serialize the list, so I can simply reload that list, if I need it.
Here is a short example of my XML definition (I store the width and height rather then the x2 and y2 values in the xml, as I find it more human readable and more convenient for manual editing. After deserialization I calculate the x2 and y1 values):
<spriteSheet imageName="buildings" name="buildings">
<sprite name="1x2 industry 01" spriteX="0" spriteY="0" width="50" height="112"/>
<sprite name="1x2 quarters 01" spriteX="50" spriteY="0" width="50" height="112"/>
<sprite name="1x1 spaceport 01" spriteX="243" spriteY="112" width="51" height="56"/>
...
</spriteSheet>
I am trying to test if a point lies within a circle and if the point is on the perimeter, it should be included in the results. However, Java's contains() implementation uses less than instead of less than or equal to. For example consider this snippet:
Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 100, 100);
System.out.println(circle.contains(50, 0));
System.out.println(circle.contains(50, 100));
System.out.println(circle.contains(0, 50));
System.out.println(circle.contains(100, 50));
System.out.println(circle.contains(50, 50));
This prints the following:
false
false
false
false
true
How can I achieve a value of true for all of those cases?
You have to decide what kind of tolerance your method will use. While your example uses points that are expressible in floating point, there are many points along the border of the ellipse which will not be, and so deciding whether a point is "on the border" isn't clear-cut. If you don't much care, then I would suggest making the ellipse slightly "bigger" than you actually want and using the built-in contains() method.
If you want to write your own method, it's as simple as taking the formula for an ellipse, plugging in the X and Y values of the point you wish to test, and observing the result:
bool isInsideOfOrOnBorderOfEllipse = ((x*x)/(a*a) + (y*y)/(b*b)) <= 1;
Note that this still runs into the problem of non-representable points, so some points that you think should be "on the border" won't be.
Update: Given that you're just using the built-in ellipse object (and thus specifying height/width rather than the general ellipse parameters) it would be worthwhile to have a look at the source for contains() here: http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/ffa98eed5766/src/share/classes/java/awt/geom/Ellipse2D.java
Derive a new class, and then override contains(). In the overridden version, just copy the code, except use <= instead of < and you should be good.
You could use the method intersects. As javadoc says: Tests if the interior of this Ellipse2D intersects the interior of a specified rectangular area. Although it is not a circle (best representation of a tolerance around a point) works pretty well
This snippet should work for any x, y you want to check:
int size = 2;
...
ellipse.intersects(x - (size/2), y - (size/2), size, size);
It is just a rectangle around the point of interest. More size, nore tolerance
Maybe getDistance() can help you here? Points on the prerimeter should return 0.