下面列出了java.awt.Graphics2D#transform ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void paintPageError(Graphics2D grx)
{
AffineTransform origTransform = grx.getTransform();
AffineTransform transform = new AffineTransform();
transform.translate(1, 1);
transform.scale(realZoom, realZoom);
grx.transform(transform);
try
{
drawPageError(grx);
}
finally
{
grx.setTransform(origTransform);
}
}
/**
* Draws the attributed string at <code>(textX, textY)</code>, rotated by
* the specified angle about <code>(rotateX, rotateY)</code>.
*
* @param text the attributed string (<code>null</code> not permitted).
* @param g2 the graphics output target.
* @param textX the x-coordinate for the text.
* @param textY the y-coordinate for the text.
* @param angle the rotation angle (in radians).
* @param rotateX the x-coordinate for the rotation point.
* @param rotateY the y-coordinate for the rotation point.
*
* @since 1.0.16
*/
public static void drawRotatedString(AttributedString text, Graphics2D g2,
float textX, float textY, double angle, float rotateX,
float rotateY) {
ParamChecks.nullNotPermitted(text, "text");
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle,
rotateX, rotateY);
g2.transform(rotate);
TextLayout tl = new TextLayout(text.getIterator(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
g2.setTransform(saved);
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
double theta = Math.toRadians(15);
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double xsize = sin * h + cos * w;
double ysize = sin * w + cos * h;
double scale = Math.min(w / xsize, h / ysize);
xsize *= scale;
ysize *= scale;
AffineTransform at = new AffineTransform();
at.translate((w - xsize) / 2.0, (h - ysize) / 2.0);
at.translate(sin * h * scale, 0.0);
at.rotate(theta);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Creates an BufferedImage and draws a text, using two transformations,
* one for graphics and one for font.
*/
private static BufferedImage createImage(final boolean aa,
final AffineTransform gtx,
final AffineTransform ftx) {
final BufferedImage bi = new BufferedImage(SIZE, SIZE, TYPE_INT_RGB);
final Graphics2D bg = bi.createGraphics();
bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
aa ? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF);
bg.setColor(Color.RED);
bg.fillRect(0, 0, SIZE, SIZE);
bg.translate(100, 100);
bg.transform(gtx);
bg.setColor(Color.BLACK);
bg.setFont(bg.getFont().deriveFont(20.0f).deriveFont(ftx));
bg.drawString(STR, 0, 0);
bg.dispose();
return bi;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
/**
* Creates and returns a buffered image into which the chart has been drawn.
*
* @param imageWidth the image width.
* @param imageHeight the image height.
* @param drawWidth the width for drawing the chart (will be scaled to
* fit image).
* @param drawHeight the height for drawing the chart (will be scaled to
* fit image).
* @param info optional object for collection chart dimension and entity
* information.
*
* @return A buffered image.
*/
public BufferedImage createBufferedImage(int imageWidth,
int imageHeight,
double drawWidth,
double drawHeight,
ChartRenderingInfo info) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
double scaleX = imageWidth / drawWidth;
double scaleY = imageHeight / drawHeight;
AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY);
g2.transform(st);
draw(g2, new Rectangle2D.Double(0, 0, drawWidth, drawHeight), null,
info);
g2.dispose();
return image;
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
double theta = Math.toRadians(15);
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double xsize = sin * h + cos * w;
double ysize = sin * w + cos * h;
double scale = Math.min(w / xsize, h / ysize);
xsize *= scale;
ysize *= scale;
AffineTransform at = new AffineTransform();
at.translate((w - xsize) / 2.0, (h - ysize) / 2.0);
at.translate(sin * h * scale, 0.0);
at.rotate(theta);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
@Override
protected void paintComponent(Graphics g) {
int min = Math.min(getWidth(), getHeight());
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.transform(TransformUtils.createAffineTransform(new Rectangle(0,
0, 300, 300), new Rectangle(getWidth() / 2 - min / 2,
getHeight() / 2 - min / 2, min, min)));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int shapeIndex = ((Number) shapeIndexSpinner.getValue()).intValue() - 1;
int type = typeComboBox.getSelectedIndex();
GeneralPath s = p[type][shapeIndex];
g2.setColor(Color.white);
g2.fillRect(0, 0, 300, 300);
g2.setColor(Color.blue);
g2.fill(s);
GeneralPath s2 = Clipper.clipToRect(s, null, r);
g2.setColor(new Color(0, 255, 0, 120));
g2.fill(s2);
PathIterator i = s.getPathIterator(null);
float[] f2 = new float[6];
g.setColor(Color.red);
while (i.isDone() == false) {
int k = i.currentSegment(f2);
if (k == PathIterator.SEG_MOVETO) {
g2.fill(new Ellipse2D.Float(f2[0] - 2, f2[1] - 2, 4, 4));
} else if (k == PathIterator.SEG_LINETO) {
g2.draw(new Ellipse2D.Float(f2[0] - 2, f2[1] - 2, 4, 4));
} else if (k == PathIterator.SEG_QUADTO) {
g2.draw(new Ellipse2D.Float(f2[2] - 2, f2[3] - 2, 4, 4));
} else if (k == PathIterator.SEG_CUBICTO) {
g2.draw(new Ellipse2D.Float(f2[4] - 2, f2[5] - 2, 4, 4));
}
i.next();
}
g2.setColor(new Color(0, 0, 0, 120));
g2.draw(r);
}
/**
* Draws a shape with the specified rotation about <code>(x, y)</code>.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param shape the shape (<code>null</code> not permitted).
* @param angle the angle (in radians).
* @param x the x coordinate for the rotation point.
* @param y the y coordinate for the rotation point.
*/
public static void drawRotatedShape(Graphics2D g2, Shape shape,
double angle, float x, float y) {
AffineTransform saved = g2.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(angle, x, y);
g2.transform(rotate);
g2.draw(shape);
g2.setTransform(saved);
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
AffineTransform at = new AffineTransform();
at.translate(0.0, (h - (w*h)/(w + h*0.1)) / 2);
at.shear(0.1, 0.0);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
private Graphics createVerticalMirrorGraphics(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform transform = AffineTransform.getScaleInstance(1, -1);
transform.translate(0, -getHeight());
g2d.transform(transform);
return g2d;
}
/**
* Fills the area of text using green solid color.
*/
private static void fillTextArea(final BufferedImage bi,
final AffineTransform tx1,
final AffineTransform tx2) {
final Graphics2D bg = bi.createGraphics();
bg.translate(100, 100);
bg.transform(tx1);
bg.transform(tx2);
bg.setColor(Color.GREEN);
final Font font = bg.getFont().deriveFont(20.0f);
bg.setFont(font);
bg.fill(font.getStringBounds(STR, bg.getFontRenderContext()));
bg.dispose();
}
private void tlDrawLine( Graphics2D g2, TextLayout tl,
float baseX, float baseY ) {
/// ABP - keep track of old tform, restore it later
AffineTransform oldTx = null;
oldTx = g2.getTransform();
g2.translate( baseX, baseY );
g2.transform( getAffineTransform( g2Transform ) );
tl.draw( g2, (float) 0, (float) 0 );
/// ABP - restore old tform
g2.setTransform ( oldTx );
}
ProjectMetagonEditGrammarIconImage(ProjectMetagon pm,int span){
super(span,span,BufferedImage.TYPE_INT_RGB);
//init image
Path2D path=pm.getImagePath();
Graphics2D g=createGraphics();
g.setRenderingHints(UI.RENDERING_HINTS);
//fill background
g.setColor(UI.ELEMENTMENU_ICONBACKGROUND);
g.fillRect(0,0,span,span);
//glean metrics and transform
Rectangle2D pbounds=path.getBounds2D();
double pw=pbounds.getWidth(),ph=pbounds.getHeight(),scale;
int maxpolygonimagespan=span-(UI.ELEMENTMENU_ICONGEOMETRYINSET*2);
scale=(pw>ph)?maxpolygonimagespan/pw:maxpolygonimagespan/ph;
AffineTransform t=new AffineTransform();
t.scale(scale,-scale);//note y flip
double
xoffset=-pbounds.getMinX()+(((span-(pw*scale))/2)/scale),
yoffset=-pbounds.getMaxY()-(((span-(ph*scale))/2)/scale);
t.translate(xoffset,yoffset);
g.transform(t);
//fill metagon
//use color to distinguish protojig counts
int pjcount=pm.getJigCount();
if(pjcount<UI.GRAMMAR_EDITOR_METAGON_ICONS_FILLCOLOR.length)
g.setColor(UI.GRAMMAR_EDITOR_METAGON_ICONS_FILLCOLOR[pjcount]);
else
g.setColor(UI.GRAMMAR_EDITOR_METAGON_ICONS_FILLCOLOR[UI.GRAMMAR_EDITOR_METAGON_ICONS_FILLCOLOR.length-1]);
g.fill(path);
//stroke it
g.setColor(UI.ELEMENTMENU_ICON_STROKE);
g.setStroke(new BasicStroke(
(float)(UI.ELEMENTMENU_ICONPATHSTROKETHICKNESS/scale),
BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_ROUND,
0,null,0));
g.draw(path);}
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default");
final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator);
final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored
final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
final int height = Integer.parseInt(captchaSizeConfigs[1]);
final int width = Integer.parseInt(captchaSizeConfigs[2]);
final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6);
final char[] availableChars = EntityUtilProperties.getPropertyValue("captcha", "captcha.characters", delegator).toCharArray();
//It is possible to pass the font size, image width and height with the request as well
Color backgroundColor = Color.gray;
Color borderColor = Color.DARK_GRAY;
Color textColor = Color.ORANGE;
Color circleColor = new Color(160, 160, 160);
Font textFont = new Font("Arial", Font.PLAIN, fontSize);
int circlesToDraw = 6;
float horizMargin = 20.0f;
double rotationRange = 0.7; // in radians
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
//Generating some circles for background noise
g.setColor(circleColor);
for (int i = 0; i < circlesToDraw; i++) {
int circleRadius = (int) (Math.random() * height / 2.0);
int circleX = (int) (Math.random() * width - circleRadius);
int circleY = (int) (Math.random() * height - circleRadius);
g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
}
g.setColor(textColor);
g.setFont(textFont);
FontMetrics fontMetrics = g.getFontMetrics();
int maxAdvance = fontMetrics.getMaxAdvance();
int fontHeight = fontMetrics.getHeight();
String captchaCode = RandomStringUtils.random(6, availableChars);
float spaceForLetters = -horizMargin * 2 + width;
float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
for (int i = 0; i < captchaCode.length(); i++) {
// this is a separate canvas used for the character so that
// we can rotate it independently
int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
int charDim = Math.max(maxAdvance, fontHeight);
int halfCharDim = (charDim / 2);
BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
Graphics2D charGraphics = charImage.createGraphics();
charGraphics.translate(halfCharDim, halfCharDim);
double angle = (Math.random() - 0.5) * rotationRange;
charGraphics.transform(AffineTransform.getRotateInstance(angle));
charGraphics.translate(-halfCharDim, -halfCharDim);
charGraphics.setColor(textColor);
charGraphics.setFont(textFont);
int charX = (int) (0.5 * charDim - 0.5 * charWidth);
charGraphics.drawString("" + captchaCode.charAt(i), charX,
((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));
float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
int y = ((height - charDim) / 2);
g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);
charGraphics.dispose();
}
// Drawing the image border
g.setColor(borderColor);
g.drawRect(0, 0, width - 1, height - 1);
g.dispose();
response.setContentType("image/jpeg");
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
HttpSession session = request.getSession();
Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
if (captchaCodeMap == null) {
captchaCodeMap = new HashMap<>();
session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
}
captchaCodeMap.put(captchaCodeId, captchaCode);
} catch (IOException | IllegalArgumentException | IllegalStateException ioe) {
Debug.logError(ioe.getMessage(), module);
}
return "success";
}
public void init(TestEnvironment env, Result result) {
// graphics
graphics = env.getGraphics();
// text
String sname = (String)env.getModifier(tscriptList);
int slen = env.getIntValue(tlengthList);
text = getString(sname, slen);
// chars
chars = text.toCharArray();
// font
String fname = (String)env.getModifier(fnameList);
if ("Physical".equals(fname)) {
fname = physicalFontNameFor(sname, slen, text);
}
int fstyle = env.getIntValue(fstyleList);
float fsize = ((Float)env.getModifier(fsizeList)).floatValue();
AffineTransform ftx = (AffineTransform)env.getModifier(ftxList);
font = new Font(fname, fstyle, (int)fsize);
if (hasGraphics2D) {
if (fsize != Math.floor(fsize)) {
font = font.deriveFont(fsize);
}
if (!ftx.isIdentity()) {
font = font.deriveFont(ftx);
}
}
// graphics
if (hasGraphics2D) {
Graphics2D g2d = (Graphics2D)graphics;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
env.getModifier(taaList));
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
env.isEnabled(tfmTog)
? RenderingHints.VALUE_FRACTIONALMETRICS_ON
: RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
env.isEnabled(gaaTog)
? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.transform((AffineTransform)env.getModifier(gtxList));
}
// set result
result.setUnits(text.length());
result.setUnitName("char");
}