use of java.awt.geom.Rectangle2D in project scriptographer by scriptographer.
the class Raster method getAverageColor.
/**
* @jshide
*/
public Color getAverageColor(Shape shape) {
// Rectangle2D rect = shape.getBounds2D();
GeneralPath path;
int width = getWidth();
int height = getHeight();
int startX = 0;
int startY = 0;
if (shape != null) {
Matrix inverse = getInverseMatrix();
if (inverse == null)
return null;
// Create a transformed path. This is faster than
// path.clone() / path.transform(at);
PathIterator pi = shape.getPathIterator(inverse.toAffineTransform());
path = new GeneralPath();
path.setWindingRule(pi.getWindingRule());
path.append(pi, false);
Rectangle2D bounds = path.getBounds2D();
// Fetch the sub image to iterate over and calculate average colors
// from
// Crop to the maximum size.
Rectangle2D.intersect(bounds, new Rectangle2D.Double(startX, startY, width, height), bounds);
width = (int) Math.ceil(bounds.getWidth());
height = (int) Math.ceil(bounds.getHeight());
// Are we completely outside the raster? If so, return null
if (width <= 0 || height <= 0)
return null;
startX = (int) Math.floor(bounds.getX());
startY = (int) Math.floor(bounds.getY());
} else {
path = null;
}
BufferedImage img = getSubImage(startX, startY, width, height);
// Raster check = new Raster(img);
// check.setPosition(rect.getCenterX(), rect.getCenterY());
WritableRaster raster = img.getRaster();
byte[] data = (byte[]) raster.getDataElements(0, 0, null);
float[] components = new float[data.length];
for (int i = 0; i < data.length; i++) components[i] = data[i] & 0xff;
long total = 1;
for (int y = 0; y < height; y++) {
for (int x = (y == 0) ? 1 : 0; x < width; x++) {
if (path == null || path.contains(x + startX, y + startY)) {
data = (byte[]) raster.getDataElements(x, height - 1 - y, data);
for (int i = 0; i < data.length; i++) components[i] += data[i] & 0xff;
total++;
}
}
}
total *= 255;
for (int i = 0; i < components.length; i++) components[i] = components[i] / total;
// Return colors
if (components.length == 4)
return new CMYKColor(components);
else if (components.length == 3)
return new RGBColor(components);
else
return new GrayColor(components);
}
use of java.awt.geom.Rectangle2D in project jgnash by ccavanaugh.
the class PrintableCheckLayout method drawSheet.
/**
* Paint a sheet on checks on the graphics device given an array of
* transactions. If the array is null, it is assumed that a test print is
* being requested, otherwise, only non null transactions will be printed.
* The array must equal getNumChecks. Check position will not be assumed.
*
* @param g2 graphics context to draw on
* @param format page format to use
* @param list array of transactions
*/
private void drawSheet(final Graphics2D g2, final PageFormat format, final Transaction[] list) {
double checkHeight = checkLayout.getCheckHeight();
int numChecks = checkLayout.getNumberOfChecks();
for (int i = 0; i < numChecks; i++) {
Rectangle2D bounds = new Rectangle2D.Double(0, i * checkHeight, format.getWidth(), checkHeight);
if (list != null) {
if (list.length != getNumChecks()) {
return;
}
if (list[i] != null) {
// skip null transactions
String payee = list[i].getPayee();
String memo = list[i].getMemo();
BigDecimal amount = list[i].getAmount(list[i].getCommonAccount()).abs();
LocalDate date = list[i].getLocalDate();
drawCheck(g2, bounds, amount, date, memo, payee);
}
} else {
String payee = "Expensive bank USA";
String memo = "I spent too much on the widget";
BigDecimal amount = new BigDecimal("12345.67");
LocalDate date = LocalDate.now();
drawCheck(g2, bounds, amount, date, memo, payee);
}
}
}
use of java.awt.geom.Rectangle2D in project jgnash by ccavanaugh.
the class PrintPreviewPanel method paintComponent.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// x offset of page start in window
double xOffset;
// y offset of page start in window
double yOffset;
// scale factor to fit page in window
double scale;
double px = pageFormat.getWidth();
double py = pageFormat.getHeight();
double sx = getWidth() - 1;
double sy = getHeight() - 1;
if (px / py < sx / sy) {
// center horizontally
scale = sy / py;
xOffset = 0.5 * (sx - scale * px);
yOffset = 0;
} else {
// center vertically
scale = sx / px;
xOffset = 0;
yOffset = 0.5 * (sy - scale * py);
}
g2.translate((float) xOffset, (float) yOffset);
g2.scale((float) scale, (float) scale);
// draw page outline (ignoring margins)
Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
g2.setPaint(Color.WHITE);
g2.fill(page);
g2.setPaint(Color.BLACK);
g2.draw(page);
// draw the outline of the margin
Rectangle2D margin = new Rectangle2D.Double(pageFormat.getImageableX(), pageFormat.getImageableY(), pageFormat.getImageableWidth(), pageFormat.getImageableHeight());
g2.setPaint(Color.DARK_GRAY);
g2.draw(margin);
// reset the color
g2.setPaint(Color.BLACK);
try {
printable.print(g2, pageFormat, 0);
} catch (PrinterException e) {
Logger.getLogger(PrintPreviewPanel.class.getName()).log(Level.INFO, e.getLocalizedMessage(), e);
}
}
use of java.awt.geom.Rectangle2D in project jdk8u_jdk by JetBrains.
the class RenderTests method makeTexturePaint.
private TexturePaint makeTexturePaint(int size, boolean alpha) {
int s2 = size / 2;
int type = alpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
BufferedImage img = new BufferedImage(size, size, type);
Color[] colors = makeGradientColors(4, alpha);
Graphics2D g2d = img.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setColor(colors[0]);
g2d.fillRect(0, 0, s2, s2);
g2d.setColor(colors[1]);
g2d.fillRect(s2, 0, s2, s2);
g2d.setColor(colors[3]);
g2d.fillRect(0, s2, s2, s2);
g2d.setColor(colors[2]);
g2d.fillRect(s2, s2, s2, s2);
g2d.dispose();
Rectangle2D bounds = new Rectangle2D.Float(0, 0, size, size);
return new TexturePaint(img, bounds);
}
use of java.awt.geom.Rectangle2D in project jdk8u_jdk by JetBrains.
the class WPathGraphics method drawString.
/**
* Renders the text specified by the specified <code>String</code>,
* using the current <code>Font</code> and <code>Paint</code> attributes
* in the <code>Graphics2D</code> context.
* The baseline of the first character is at position
* (<i>x</i>, <i>y</i>) in the User Space.
* The rendering attributes applied include the <code>Clip</code>,
* <code>Transform</code>, <code>Paint</code>, <code>Font</code> and
* <code>Composite</code> attributes. For characters in script systems
* such as Hebrew and Arabic, the glyphs can be rendered from right to
* left, in which case the coordinate supplied is the location of the
* leftmost character on the baseline.
* @param s the <code>String</code> to be rendered
* @param x, y the coordinates where the <code>String</code>
* should be rendered
* @see #setPaint
* @see java.awt.Graphics#setColor
* @see java.awt.Graphics#setFont
* @see #setTransform
* @see #setComposite
* @see #setClip
*/
@Override
public void drawString(String str, float x, float y, Font font, FontRenderContext frc, float targetW) {
if (str.length() == 0) {
return;
}
if (WPrinterJob.shapeTextProp) {
super.drawString(str, x, y, font, frc, targetW);
return;
}
/* If the Font has layout attributes we need to delegate to TextLayout.
* TextLayout renders text as GlyphVectors. We try to print those
* using printer fonts - ie using Postscript text operators so
* we may be reinvoked. In that case the "!printingGlyphVector" test
* prevents us recursing and instead sends us into the body of the
* method where we can safely ignore layout attributes as those
* are already handled by TextLayout.
* Similarly if layout is needed based on the text, then we
* delegate to TextLayout if possible, or failing that we delegate
* upwards to filled shapes.
*/
boolean layoutNeeded = strNeedsTextLayout(str, font);
if ((font.hasLayoutAttributes() || layoutNeeded) && !printingGlyphVector) {
TextLayout layout = new TextLayout(str, font, frc);
layout.draw(this, x, y);
return;
} else if (layoutNeeded) {
super.drawString(str, x, y, font, frc, targetW);
return;
}
AffineTransform deviceTransform = getTransform();
AffineTransform fontTransform = new AffineTransform(deviceTransform);
fontTransform.concatenate(font.getTransform());
int transformType = fontTransform.getType();
/* Use GDI for the text if the graphics transform is something
* for which we can obtain a suitable GDI font.
* A flip or shearing transform on the graphics or a transform
* on the font force us to decompose the text into a shape.
*/
boolean directToGDI = ((transformType != AffineTransform.TYPE_GENERAL_TRANSFORM) && ((transformType & AffineTransform.TYPE_FLIP) == 0));
WPrinterJob wPrinterJob = (WPrinterJob) getPrinterJob();
try {
wPrinterJob.setTextColor((Color) getPaint());
} catch (ClassCastException e) {
// peek should detect such paints.
directToGDI = false;
}
if (!directToGDI) {
super.drawString(str, x, y, font, frc, targetW);
return;
}
/* Now we have checked everything is OK to go through GDI as text
* with the exception of testing GDI can find and use the font. That
* is handled in the textOut() call.
*/
/* Compute the starting position of the string in
* device space.
*/
Point2D.Float userpos = new Point2D.Float(x, y);
Point2D.Float devpos = new Point2D.Float();
/* Already have the translate from the deviceTransform,
* but the font may have a translation component too.
*/
if (font.isTransformed()) {
AffineTransform fontTx = font.getTransform();
float translateX = (float) (fontTx.getTranslateX());
float translateY = (float) (fontTx.getTranslateY());
if (Math.abs(translateX) < 0.00001)
translateX = 0f;
if (Math.abs(translateY) < 0.00001)
translateY = 0f;
userpos.x += translateX;
userpos.y += translateY;
}
deviceTransform.transform(userpos, devpos);
if (getClip() != null) {
deviceClip(getClip().getPathIterator(deviceTransform));
}
/* Get the font size in device coordinates.
* The size needed is the font height scaled to device space.
* Although we have already tested that there is no shear,
* there may be a non-uniform scale, so the width of the font
* does not scale equally with the height. That is handled
* by specifying an 'average width' scale to GDI.
*/
float fontSize = font.getSize2D();
double devResX = wPrinterJob.getXRes();
double devResY = wPrinterJob.getYRes();
double fontDevScaleY = devResY / DEFAULT_USER_RES;
int orient = getPageFormat().getOrientation();
if (orient == PageFormat.LANDSCAPE || orient == PageFormat.REVERSE_LANDSCAPE) {
double tmp = devResX;
devResX = devResY;
devResY = tmp;
}
double devScaleX = devResX / DEFAULT_USER_RES;
double devScaleY = devResY / DEFAULT_USER_RES;
fontTransform.scale(1.0 / devScaleX, 1.0 / devScaleY);
Point2D.Double pty = new Point2D.Double(0.0, 1.0);
fontTransform.deltaTransform(pty, pty);
double scaleFactorY = Math.sqrt(pty.x * pty.x + pty.y * pty.y);
float scaledFontSizeY = (float) (fontSize * scaleFactorY * fontDevScaleY);
Point2D.Double ptx = new Point2D.Double(1.0, 0.0);
fontTransform.deltaTransform(ptx, ptx);
double scaleFactorX = Math.sqrt(ptx.x * ptx.x + ptx.y * ptx.y);
float awScale = getAwScale(scaleFactorX, scaleFactorY);
int iangle = getAngle(ptx);
ptx = new Point2D.Double(1.0, 0.0);
deviceTransform.deltaTransform(ptx, ptx);
double advanceScaleX = Math.sqrt(ptx.x * ptx.x + ptx.y * ptx.y);
pty = new Point2D.Double(0.0, 1.0);
deviceTransform.deltaTransform(pty, pty);
double advanceScaleY = Math.sqrt(pty.x * pty.x + pty.y * pty.y);
Font2D font2D = FontUtilities.getFont2D(font);
if (font2D instanceof TrueTypeFont) {
textOut(str, font, (TrueTypeFont) font2D, frc, scaledFontSizeY, iangle, awScale, advanceScaleX, advanceScaleY, x, y, devpos.x, devpos.y, targetW);
} else if (font2D instanceof CompositeFont) {
/* Composite fonts are made up of multiple fonts and each
* substring that uses a particular component font needs to
* be separately sent to GDI.
* This works for standard composite fonts, alternate ones,
* Fonts that are a physical font backed by a standard composite,
* and with fallback fonts.
*/
CompositeFont compFont = (CompositeFont) font2D;
float userx = x, usery = y;
float devx = devpos.x, devy = devpos.y;
char[] chars = str.toCharArray();
int len = chars.length;
int[] glyphs = new int[len];
compFont.getMapper().charsToGlyphs(len, chars, glyphs);
int startChar = 0, endChar = 0, slot = 0;
while (endChar < len) {
startChar = endChar;
slot = glyphs[startChar] >>> 24;
while (endChar < len && ((glyphs[endChar] >>> 24) == slot)) {
endChar++;
}
String substr = new String(chars, startChar, endChar - startChar);
PhysicalFont slotFont = compFont.getSlotFont(slot);
textOut(substr, font, slotFont, frc, scaledFontSizeY, iangle, awScale, advanceScaleX, advanceScaleY, userx, usery, devx, devy, 0f);
Rectangle2D bds = font.getStringBounds(substr, frc);
float xAdvance = (float) bds.getWidth();
userx += xAdvance;
userpos.x += xAdvance;
deviceTransform.transform(userpos, devpos);
devx = devpos.x;
devy = devpos.y;
}
} else {
super.drawString(str, x, y, font, frc, targetW);
}
}
Aggregations