下面列出了怎么用java.awt.geom.Dimension2D的API类实例代码及写法,或者点击链接到github查看源代码。
public static void render( Graphics2D gc, GraphicsNode svgGraphicsNode, Dimension2D svgGraphicsSize, int centerX,
int centerY, int width, int height, double angleRadians ) {
double scaleX = width / svgGraphicsSize.getWidth();
double scaleY = height / svgGraphicsSize.getHeight();
AffineTransform affineTransform = new AffineTransform();
if ( centerX != 0 || centerY != 0 ) {
affineTransform.translate( centerX, centerY );
}
affineTransform.scale( scaleX, scaleY );
if ( angleRadians != 0 ) {
affineTransform.rotate( angleRadians );
}
affineTransform.translate( -svgGraphicsSize.getWidth() / 2, -svgGraphicsSize.getHeight() / 2 );
svgGraphicsNode.setTransform( affineTransform );
svgGraphicsNode.paint( gc );
}
@Override
public Dimension2D getDimension(JasperReportsContext jasperReportsContext)
{
Dimension2D imageDimension = null;
try
{
// use original dimension if possible
imageDimension = renderer.getDimension(jasperReportsContext);
}
catch (JRException e)
{
// ignore
}
if (imageDimension == null)
{
// fallback to element dimension
imageDimension = elementDimension;
}
return imageDimension;
}
/**
* Returns the preferred size of the element (including insets).
*
* @param g2 the graphics target.
* @param bounds the bounds.
* @param constraints the constraints (ignored for now).
*
* @return The preferred size.
*/
@Override
public Dimension2D preferredSize(Graphics2D g2, Rectangle2D bounds,
Map<String, Object> constraints) {
Insets insets = getInsets();
double[][] cellDimensions = findCellDimensions(g2, bounds);
double[] widths = cellDimensions[0];
double[] heights = cellDimensions[1];
double w = insets.left + insets.right;
for (int i = 0; i < widths.length; i++) {
w = w + widths[i];
}
double h = insets.top + insets.bottom;
for (int i = 0; i < heights.length; i++) {
h = h + heights[i];
}
return new Dimension((int) w, (int) h);
}
public void applyTransforms() {
double scaleX = getScaleX();
double scaleY = getScaleY();
for (Bounds bounds : this.bounds) {
if (bounds instanceof QBounds) {
QBounds qBounds = (QBounds) bounds;
Point2D point = qBounds.getLocation();
qBounds.setLocation(new Point2D.Double(point.getX()
+ translate.getX(), point.getY() + translate.getY()));
Dimension2D d = qBounds.getSize();
qBounds.setSize(new Dimension2DImpl(d.getWidth() * scaleX, d
.getHeight()
* scaleY));
}
}
clear();
}
/**
* Returns the preferred size of the element (including insets).
*
* @param g2 the graphics target.
* @param bounds the bounds.
* @param constraints the constraints (ignored for now).
*
* @return The preferred size.
*/
@Override
public Dimension2D preferredSize(Graphics2D g2, Rectangle2D bounds,
Map<String, Object> constraints) {
Insets insets = getInsets();
double width = insets.left + insets.right;
double height = insets.top + insets.bottom;
double maxRowWidth = 0.0;
int elementCount = this.elements.size();
int i = 0;
while (i < elementCount) {
// get one row of elements...
List<ElementInfo> elementsInRow = rowOfElements(i, g2,
bounds);
double rowHeight = calcRowHeight(elementsInRow);
double rowWidth = calcRowWidth(elementsInRow, this.hgap);
maxRowWidth = Math.max(rowWidth, maxRowWidth);
height += rowHeight;
i = i + elementsInRow.size();
}
width += maxRowWidth;
return new ElementDimension(width, height);
}
@Test
public void testPreferredSize1() {
BufferedImage img = new BufferedImage(100, 50,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
FlowElement fe = new FlowElement();
ShapeElement se1 = new ShapeElement(new Rectangle(10, 5), Color.BLACK);
se1.setInsets(new Insets(0, 0, 0, 0));
fe.addElement(se1);
Dimension2D dim = fe.preferredSize(g2, new Rectangle(100, 50));
assertEquals(14.0, dim.getWidth(), EPSILON);
assertEquals(9.0, dim.getHeight(), EPSILON);
// although this element looks at the width of the bounds to determine
// the layout, it will still return the minimum required size as the
// preferred size, even if this exceeds the bounds
dim = fe.preferredSize(g2, new Rectangle(10, 5));
assertEquals(14.0, dim.getWidth(), EPSILON);
assertEquals(9.0, dim.getHeight(), EPSILON);
}
@Override
public Dimension2D preferredSize(Graphics2D g2, Rectangle2D bounds,
Map<String, Object> constraints) {
Insets insets = getInsets();
Rectangle2D shapeBounds = shape.getBounds2D();
return new ElementDimension(Math.min(shapeBounds.getWidth()
+ insets.left + insets.right, bounds.getWidth()),
Math.min(shapeBounds.getHeight() + insets.top + insets.bottom,
bounds.getHeight()));
}
/** @return A BufferedImage created from nsImagePtr, or null. */
public BufferedImage toImage() {
if (ptr == 0) return null;
final Dimension2D size = nativeGetNSImageSize(ptr);
final int w = (int)size.getWidth();
final int h = (int)size.getHeight();
final BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
final DataBufferInt dbi = (DataBufferInt)bimg.getRaster().getDataBuffer();
final int[] buffer = SunWritableRaster.stealData(dbi, 0);
nativeCopyNSImageIntoArray(ptr, buffer, w, h);
SunWritableRaster.markDirty(dbi);
return bimg;
}
/**
* Starts parsing.
*
* @param attrs the attributes.
* @throws SAXException if there is a parsing error.
*/
protected void startParsing( final Attributes attrs ) throws SAXException {
final Dimension2D pageSize = DoubleDimensionConverter.getObject( attrs.getValue( getUri(), "pageSize" ) );
final double topBorder = Double.parseDouble( attrs.getValue( getUri(), "topBorder" ) );
final double leftBorder = Double.parseDouble( attrs.getValue( getUri(), "leftBorder" ) );
final double bottomBorder = Double.parseDouble( attrs.getValue( getUri(), "bottomBorder" ) );
final double rightBorder = Double.parseDouble( attrs.getValue( getUri(), "rightBorder" ) );
final Paper paper = PageFormatFactory.getInstance().createPaper( pageSize.getWidth(), pageSize.getHeight() );
PageFormatFactory.getInstance().setBorders( paper, topBorder, leftBorder, bottomBorder, rightBorder );
pageFormat = new PageFormat();
pageFormat.setPaper( paper );
}
public MultiResolutionCachedImage(int baseImageWidth, int baseImageHeight,
Dimension2D[] sizes, BiFunction<Integer, Integer, Image> mapper) {
this.baseImageWidth = baseImageWidth;
this.baseImageHeight = baseImageHeight;
this.sizes = (sizes == null) ? null : Arrays.copyOf(sizes, sizes.length);
this.mapper = mapper;
}
@Nullable
public static BufferedImage renderMindMapAsImage(@Nonnull final MindMap model, @Nonnull final MindMapPanelConfig cfg, final boolean expandAll, @Nonnull final RenderQuality quality) {
final MindMap workMap = new MindMap(model);
workMap.resetPayload();
if (expandAll) {
MindMapUtils.removeCollapseAttr(workMap);
}
final Dimension2D blockSize = calculateSizeOfMapInPixels(workMap, null, cfg, expandAll, quality);
if (blockSize == null) {
return null;
}
final BufferedImage img = new BufferedImage((int) blockSize.getWidth(), (int) blockSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = img.createGraphics();
final MMGraphics gfx = new MMGraphics2DWrapper(g);
try {
quality.prepare(g);
gfx.setClip(0, 0, img.getWidth(), img.getHeight());
layoutFullDiagramWithCenteringToPaper(gfx, workMap, cfg, blockSize);
drawOnGraphicsForConfiguration(gfx, cfg, workMap, false, null);
} finally {
gfx.dispose();
}
return img;
}
@Override
public List<Rectangle2D> layoutElements(Graphics2D g2, Rectangle2D bounds,
Map<String, Object> constraints) {
List<Rectangle2D> result = new ArrayList<>(1);
Dimension2D prefDim = preferredSize(g2, bounds);
Fit2D fitter = Fit2D.getNoScalingFitter(getRefPoint());
Rectangle2D dest = fitter.fit(prefDim, bounds);
result.add(dest);
return result;
}
/**
* Defines the element's minimum size.
*
* @param minimumSize
* the element's minimum size.
* @see ElementFactory#setMinimumWidth(Float)
* @see ElementFactory#setMinimumHeight(Float)
*/
public void setMinimumSize( final Dimension2D minimumSize ) {
if ( minimumSize == null ) {
this.minimumWidth = null;
this.minimumHeight = null;
} else {
this.minimumWidth = new Float( minimumSize.getWidth() );
this.minimumHeight = new Float( minimumSize.getHeight() );
}
}
/**
* Defines the element's maximum size.
*
* @param maximumSize
* the element's maximum size.
* @see ElementFactory#setMaximumWidth(Float)
* @see ElementFactory#setMaximumHeight(Float)
*/
public void setMaximumSize( final Dimension2D maximumSize ) {
if ( maximumSize == null ) {
this.maximumWidth = null;
this.maximumHeight = null;
} else {
this.maximumWidth = new Float( maximumSize.getWidth() );
this.maximumHeight = new Float( maximumSize.getHeight() );
}
}
/**
* Returns the defined top-right border-radius for this element. If the border radius has a non-zero width and height,
* the element's border will have a rounded top-right corner.
*
* @return the defined border-radius for the top-right corner of this element or null, if this property is undefined.
*/
public Dimension2D getBorderTopRightRadius() {
if ( borderTopRightRadiusWidth == null || borderTopRightRadiusHeight == null ) {
return null;
}
return new FloatDimension( borderTopRightRadiusWidth.floatValue(), borderTopRightRadiusHeight.floatValue() );
}
/**
* Defines the top-right border-radius for this element. If the border radius has a non-zero width and height, the
* element's border will have a rounded top-right corner.
*
* @param borderRadius
* the defined border-radius for the top-right corner of this element or null, if this property should be
* undefined.
*/
public void setBorderTopRightRadius( final Dimension2D borderRadius ) {
if ( borderRadius == null ) {
this.borderTopRightRadiusWidth = null;
this.borderTopRightRadiusHeight = null;
} else {
this.borderTopRightRadiusWidth = new Float( borderRadius.getWidth() );
this.borderTopRightRadiusHeight = new Float( borderRadius.getHeight() );
}
}
/**
* Returns the preferred size for this element.
*
* @param g2 the graphics target.
* @param bounds the available drawing space.
* @param constraints layout constraints (ignored here).
*
* @return The preferred size (never {@code null}).
*/
@Override
public Dimension2D preferredSize(Graphics2D g2, Rectangle2D bounds,
Map<String, Object> constraints) {
g2.setFont(this.font);
FontMetrics fm = g2.getFontMetrics();
Range r = this.scale.getRange();
String minStr = this.formatter.format(r.getMin());
String maxStr = this.formatter.format(r.getMax());
Rectangle2D minStrBounds = TextUtils.getTextBounds(minStr, fm);
Rectangle2D maxStrBounds = TextUtils.getTextBounds(maxStr, fm);
double maxStrWidth = Math.max(minStrBounds.getWidth(),
maxStrBounds.getWidth());
Insets insets = getInsets();
double w, h;
if (this.orientation == Orientation.HORIZONTAL) {
w = Math.min(this.barLength + insets.left + insets.right,
bounds.getWidth());
h = Math.min(insets.top + this.barWidth + this.textOffset
+ minStrBounds.getHeight() + insets.bottom,
bounds.getHeight());
} else {
w = Math.min(insets.left + this.barWidth + this.textOffset
+ maxStrWidth + insets.right, bounds.getWidth());
h = Math.min(insets.top + this.barLength + this.textOffset
+ minStrBounds.getHeight() + insets.bottom,
bounds.getHeight());
}
return new ElementDimension(w, h);
}
/** @return A MultiResolution image created from nsImagePtr, or null. */
private Image toImage() {
if (ptr == 0) {
return null;
}
AtomicReference<Dimension2D> sizeRef = new AtomicReference<>();
execute(ptr -> {
sizeRef.set(nativeGetNSImageSize(ptr));
});
final Dimension2D size = sizeRef.get();
if (size == null) {
return null;
}
final int w = (int)size.getWidth();
final int h = (int)size.getHeight();
AtomicReference<Dimension2D[]> repRef = new AtomicReference<>();
execute(ptr -> {
repRef.set(nativeGetNSImageRepresentationSizes(ptr, size.getWidth(),
size.getHeight()));
});
Dimension2D[] sizes = repRef.get();
return sizes == null || sizes.length < 2 ?
new MultiResolutionCachedImage(w, h, (width, height)
-> toImage(w, h, width, height))
: new MultiResolutionCachedImage(w, h, sizes, (width, height)
-> toImage(w, h, width, height));
}
public void drawWidthDisplay(DragDisplay dd, Dimension2D size) {
Direction horEdgeDirection = getHorEdgeDirection();
String widthString = DragDisplay.getWidthDisplayString(size.getWidth());
Point2D horHalf = getHorHalfPoint();
float horX = (float) (horHalf.getX() + horEdgeDirection.dx);
float horY = (float) (horHalf.getY() + horEdgeDirection.dy);
dd.drawOneLine(widthString, horX, horY);
}
/**
* Adjusts the viewing distance so that the chart fits the specified
* size. A margin is left (see {@link #getMargin()} around the edges to
* leave room for labels etc.
*
* @param size the target size ({@code null} not permitted).
*/
public void zoomToFit(Dimension2D size) {
int w = (int) (size.getWidth() * (1.0 - this.margin));
int h = (int) (size.getHeight() * (1.0 - this.margin));
Dimension2D target = new Dimension(w, h);
Dimension3D d3d = this.drawable.getDimensions();
float distance = this.drawable.getViewPoint().optimalDistance(target,
d3d, this.drawable.getProjDistance());
this.drawable.getViewPoint().setRho(distance);
repaint();
}
/** @return A MultiResolution image created from nsImagePtr, or null. */
private Image toImage() {
if (ptr == 0) {
return null;
}
AtomicReference<Dimension2D> sizeRef = new AtomicReference<>();
execute(ptr -> {
sizeRef.set(nativeGetNSImageSize(ptr));
});
final Dimension2D size = sizeRef.get();
if (size == null) {
return null;
}
final int w = (int)size.getWidth();
final int h = (int)size.getHeight();
AtomicReference<Dimension2D[]> repRef = new AtomicReference<>();
execute(ptr -> {
repRef.set(nativeGetNSImageRepresentationSizes(ptr, size.getWidth(),
size.getHeight()));
});
Dimension2D[] sizes = repRef.get();
return sizes == null || sizes.length < 2 ?
new MultiResolutionCachedImage(w, h, (width, height)
-> toImage(w, h, width, height))
: new MultiResolutionCachedImage(w, h, sizes, (width, height)
-> toImage(w, h, width, height));
}
/**
* Defines the bottom-left border-radius for this element. If the border radius has a non-zero width and height, the
* element's border will have a rounded bottom-left corner.
*
* @param borderRadius
* the defined border-radius for the bottom-left corner of this element or null, if this property should be
* undefined.
*/
public void setBorderBottomLeftRadius( final Dimension2D borderRadius ) {
if ( borderRadius == null ) {
this.borderBottomLeftRadiusWidth = null;
this.borderBottomLeftRadiusHeight = null;
} else {
this.borderBottomLeftRadiusWidth = new Float( borderRadius.getWidth() );
this.borderBottomLeftRadiusHeight = new Float( borderRadius.getHeight() );
}
}
@Override
public Dimension2D getDimension(JasperReportsContext jasperReportsContext)
{
try
{
ensureSvg(jasperReportsContext);
return documentSize;
}
catch (JRException e)
{
throw new JRRuntimeException(e);
}
}
/**
* Create a simple scaling AffineTransform that transforms a rectangle
* bounded by (0,0,d1.widthd,d2.height) to (0,0,d2.width,d2.height)
*/
public static AffineTransform createAffineTransform(Dimension2D d1,
Dimension2D d2) {
return createAffineTransform(new Rectangle2D.Double(0, 0,
d1.getWidth(), d1.getHeight()),
new Rectangle2D.Double(0, 0, d2.getWidth(), d2.getHeight()));
}
public void setDiagramam(Diagram diagramam) {
this.diagram = diagramam;
Dimension2D size = diagramam.zoom(diagramam.getSize(), zoom);
setSize((int) floor(size.getWidth()) + 2,
(int) floor(size.getHeight()) + 2);
setPreferredSize(getSize());
}
public void applyComlumnsSize(QBounds tableBound, Diagram diagram) {
double width = getMinWidth();
double w = width / columns.length;
double x = tableBound.getLocation().getX();
for (TableColumn tableColumn : columns) {
QBounds bounds = (QBounds) diagram.getBounds(tableColumn);
Dimension2D size = bounds.getSize();
size.setSize(w, size.getHeight());
bounds.setLocation(new Point2D.Double(x, getColumnYLocation(
tableBound, size)));
tableColumn.setWidth(w);
x += w;
}
}
public void setFitZoom(double zoom, Dimension size) {
if (zoom > 10)
zoom = 10;
if (zoom < 0.1)
zoom = 0.1;
int columnCount = 1;
Dimension2D pageSize = getPageSize();
while (((pageSize.getWidth() + W_SPACE / zoom) * columnCount + pageSize
.getWidth()) * zoom < size.getWidth()) {
columnCount++;
}
setup(columnCount, zoom);
}
public void setOnePageZoom(Dimension size) {
Dimension2D pageSize = getPageSize();
int pageCount = printable.getPageCount();
if (pageCount == 0)
return;
double zoom = size.getWidth() / (pageSize.getWidth());
int columnCount = 1;
setup(columnCount, zoom);
}
/**
* Writes the content of the panel to a PNG image, using Java's ImageIO.
*
* @param e the event.
*/
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
Resources.localString("JPG_FILE_FILTER_DESCRIPTION"), "jpg");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this.panel);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (!filename.endsWith(".jpg")) {
filename = filename + ".jpg";
}
Dimension2D size = this.panel.getSize();
int w = (int) size.getWidth();
int h = (int) size.getHeight();
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
this.panel.getDrawable().draw(g2, new Rectangle(w, h));
try {
ImageIO.write(image, "jpeg", new File(filename));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
/**
* Draws the element within the specified bounds.
*
* @param g2 the graphics target ({@code null} not permitted).
* @param bounds the bounds ({@code null} not permitted).
* @param onDrawHandler an object that will receive notification before
* and after the element is drawn ({@code null} permitted).
*
* @since 1.3
*/
@Override
public void draw(Graphics2D g2, Rectangle2D bounds,
TableElementOnDraw onDrawHandler) {
if (onDrawHandler != null) {
onDrawHandler.beforeDraw(this, g2, bounds);
}
Shape savedClip = g2.getClip();
g2.clip(bounds);
// find the preferred size of the flow layout
Dimension2D prefDim = preferredSize(g2, bounds);
// fit a rectangle of this dimension to the bounds according to the
// element anchor
Fit2D fitter = Fit2D.getNoScalingFitter(getRefPoint());
Rectangle2D dest = fitter.fit(prefDim, bounds);
// perform layout within this bounding rectangle
List<Rectangle2D> layoutInfo = this.layoutElements(g2, dest, null);
// draw the elements
for (int i = 0; i < this.elements.size(); i++) {
Rectangle2D rect = layoutInfo.get(i);
TableElement element = this.elements.get(i);
element.draw(g2, rect, onDrawHandler);
}
g2.setClip(savedClip);
if (onDrawHandler != null) {
onDrawHandler.afterDraw(this, g2, bounds);
}
}