下面列出了java.awt.Graphics2D#fillRect ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected BufferedImage createTestImage(int numColors) {
IndexColorModel icm = createTestICM(numColors);
int w = numColors * 10;
int h = 20;
BufferedImage img = new BufferedImage(w, h,
BufferedImage.TYPE_BYTE_INDEXED, icm);
Graphics2D g = img.createGraphics();
for (int i = 0; i < numColors; i++) {
int rgb = icm.getRGB(i);
//System.out.printf("pixel %d, rgb %x\n", i, rgb);
g.setColor(new Color(rgb));
g.fillRect(i * 10, 0, w - i * 10, h);
}
g.dispose();
return img;
}
private static void draw(final Image img) {
float[] dashes = {200.0f, 200.0f};
BasicStroke bs = new BasicStroke(20.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
1.0f,
dashes,
0.0f);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 200, 40);
Line2D line = new Line2D.Double(400, 400, 3600, 400);
g.setColor(Color.BLACK);
g.scale(0.05, 0.05);
g.setStroke(bs);
g.draw(line);
g.dispose();
}
static void printInsets(PrintWriter html, Insets insets) {
html.println("<td>Insets (" + insets.top + "," + insets.left + "," + insets.bottom + "," + insets.right + ")</pre></td>");
int w = 50 + insets.left + insets.right;
int h = 20 + insets.top + insets.bottom;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
Composite old = g2.getComposite();
g2.setComposite(AlphaComposite.Clear);
g2.fillRect(0, 0, w, h);
g2.setComposite(old);
g2.setColor(Color.BLACK);
g2.drawRect(insets.left, insets.top, 49, 19);
g2.setColor(Color.RED);
g2.drawRect(0, 0, w - 1, h - 1);
g2.dispose();
html.println("<td>" + saveImage(img) + "</td>");
}
@Override
public void renderItems (Graphics2D g)
{
// Render seeds
for (Arc arc : arcsMap.values()) {
setColor(arc, g);
for (Point p : arc.getPoints()) {
g.fillRect(p.x, p.y, 1, 1);
}
}
// // Render artificial junction points (for vertical parts)
// for (Point p : arcsPivots) {
// g.setColor(Color.MAGENTA);
// g.fillOval(p.x, p.y, 1, 1);
// }
}
public void paintObject(Graphics2D g, double scale) {
Rectangle bounds = getBounds(scale);
if (style != null) style.setStyle(g);
Style[] styles = context.flagger.getStyles(element);
for (int i = 0; i < styles.length; i++) {
styles[i].setStyle(g);
}
if (style.isFilled()) {
Color c = g.getColor();
g.setColor(style.getBackground());
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(c);
}
Point[] tp = getTextPositions(scale);
TextLayout[] tl = getTextLines(scale);
for (int i = 0; i < tp.length; i++) {
tl[i].draw(g, tp[i].x, tp[i].y);
}
}
public static BufferedImage getEmptyImage(
final int width,
final int height,
final Color backgroundColor,
final Color outputTransparentColor,
final ColorModel defaultColorModel) {
BufferedImage emptyImage =
new BufferedImage(
defaultColorModel,
defaultColorModel.createCompatibleWritableRaster(width, height),
defaultColorModel.isAlphaPremultiplied(),
null);
final Graphics2D g2D = (Graphics2D) emptyImage.getGraphics();
final Color save = g2D.getColor();
g2D.setColor(backgroundColor);
g2D.fillRect(0, 0, emptyImage.getWidth(), emptyImage.getHeight());
g2D.setColor(save);
if (outputTransparentColor != null) {
emptyImage =
new RenderedImageAdapter(
ImageUtilities.maskColor(outputTransparentColor, emptyImage)).getAsBufferedImage();
}
return emptyImage;
}
/**
* Creates a time series chart diagram and writes it to the OutputStream.
*/
public void producePresentation(Map<String, OXFFeatureCollection> entireCollMap,
DesignOptions options, FileOutputStream out, boolean compress) throws OXFException,
IOException {
// render features:
int width = options.getWidth();
int height = options.getHeight();
Calendar begin = Calendar.getInstance();
begin.setTimeInMillis(options.getBegin());
Calendar end = Calendar.getInstance();
end.setTimeInMillis(options.getEnd());
DiagramRenderer renderer = new DiagramRenderer(false);
JFreeChart diagramChart = renderer.renderChart(entireCollMap, options, begin, end, compress);
diagramChart.removeLegend();
// draw chart into image:
BufferedImage diagramImage = new BufferedImage(width, height, TYPE_INT_RGB);
Graphics2D chartGraphics = diagramImage.createGraphics();
chartGraphics.setColor(Color.white);
chartGraphics.fillRect(0, 0, width, height);
diagramChart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));
JPEGImageWriteParam p = new JPEGImageWriteParam(null);
p.setCompressionMode(JPEGImageWriteParam.MODE_DEFAULT);
write(diagramImage, FORMAT, out);
}
@Override
public void drawIcon(Graphics2D g2, int width, int height, int percentage) {
g2.setColor(Color.WHITE);
g2.setPaint(new GradientPaint(0, 0, Color.WHITE.darker(), 0, (float) (height * 0.5), Color.WHITE, true));
g2.fillRect(0, 0, width, height);
g2.setColor(Color.GREEN);
g2.setPaint(new GradientPaint(0, 0, Color.GREEN.darker(), percentage, (float) (height * 0.5), Color.GREEN
.darker().darker(), false));
g2.fillRect(0, 0, (int) (percentage * 200d / 100d), height);
g2.setColor(Color.BLACK);
g2.drawRect(0, 0, width - 1, height - 1);
g2.dispose();
}
private static Image createTrayIconImage() {
/**
* Create a small image of a red circle to use as the icon for the tray icon
*/
int trayIconImageSize = 32;
final BufferedImage trayImage = new BufferedImage(trayIconImageSize, trayIconImageSize, BufferedImage.TYPE_INT_ARGB);
final Graphics2D trayImageGraphics = (Graphics2D) trayImage.getGraphics();
trayImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
trayImageGraphics.setColor(new Color(255, 255, 255, 0));
trayImageGraphics.fillRect(0, 0, trayImage.getWidth(), trayImage.getHeight());
trayImageGraphics.setColor(Color.red);
int trayIconImageInset = 4;
trayImageGraphics.fillOval(trayIconImageInset,
trayIconImageInset,
trayImage.getWidth() - 2 * trayIconImageInset,
trayImage.getHeight() - 2 * trayIconImageInset);
trayImageGraphics.setColor(Color.darkGray);
trayImageGraphics.drawOval(trayIconImageInset,
trayIconImageInset,
trayImage.getWidth() - 2 * trayIconImageInset,
trayImage.getHeight() - 2 * trayIconImageInset);
return trayImage;
}
/**
* Clear a transparent image to 100% transparent
*
* @param img The image to clear
*/
static void clearImage(BufferedImage img) {
Graphics2D g2 = img.createGraphics();
g2.setComposite(AlphaComposite.Clear);
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
g2.dispose();
}
public void fillTransparent() {
// Make all pixels transparent
Graphics2D g = (Graphics2D) getGraphics();
g.setComposite(AlphaComposite.Src);
g.setColor(new Color(0, 0, 0, 0f));
g.fillRect(0, 0, getWidth(), getHeight());
}
private static final Image clearImage(Image bb) {
Graphics2D g = (Graphics2D)bb.getGraphics();
int w = bb.getWidth(null);
int h = bb.getHeight(null);
g.setComposite(AlphaComposite.Src);
g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, w, h);
return bb;
}
private static VolatileImage getVolatileImage(GraphicsConfiguration gc,
int size) {
VolatileImage vi = gc.createCompatibleVolatileImage(size, size);
Graphics2D g2d = vi.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, size, size);
return vi;
}
public void test() throws IOException
{
for (int count = 1; count < MAX_RECTS; count++)
{
for (int r = 0; r < ITERATIONS; r++)
{
Random rand = new Random(count << 16 | r);
String id = count + "rects_iteration" + r;
log.info(id);
BufferedImage wanted = new BufferedImage(WIDTH, WIDTH, BufferedImage.TYPE_BYTE_BINARY);
BufferedImage got = new BufferedImage(WIDTH, WIDTH, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D wg = wanted.createGraphics();
wg.setColor(Color.WHITE);
Graphics2D gg = got.createGraphics();
gg.setColor(Color.WHITE);
List<RectangleUnion.Rectangle> rects = new ArrayList<>(count);
for (int i = 0; i < count; i++)
{
int x1, y1, x2, y2;
do
{
x1 = rand.nextInt(WIDTH);
x2 = rand.nextInt(WIDTH);
}
while (x1 >= x2);
do
{
y1 = rand.nextInt(WIDTH);
y2 = rand.nextInt(WIDTH);
}
while (y1 >= y2);
RectangleUnion.Rectangle rect = new RectangleUnion.Rectangle(x1, y1, x2, y2);
log.trace("{}", rect);
rects.add(rect);
wg.fillRect(x1, y1, x2 - x1, y2 - y1);
}
Shape union = RectangleUnion.union(rects);
gg.fill(union);
loop:
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < WIDTH; y++)
{
if (wanted.getRGB(x, y) != got.getRGB(x, y))
{
File tmp = new File(System.getProperty("java.io.tmpdir"));
ImageIO.write(wanted, "png", new File(tmp, id + "_wanted.png"));
ImageIO.write(got, "png", new File(tmp, id + "_got.png"));
Assert.fail(id);
break loop;
}
}
}
}
}
}
@Override
public synchronized void paintTrack(Graphics g) {
int mode = colorPicker.getMode();
if(mode==ColorPicker.HUE || mode==ColorPicker.BRI || mode==ColorPicker.SAT) {
float[] hsb = colorPicker.getHSB();
if(mode==ColorPicker.HUE) {
for(int y = 0; y<trackRect.height; y++) {
float hue = ((float)y)/((float)trackRect.height);
intArray[y] = Color.HSBtoRGB( hue, 1, 1);
}
} else if(mode==ColorPicker.SAT) {
for(int y = 0; y<trackRect.height; y++) {
float sat = 1-((float)y)/((float)trackRect.height);
intArray[y] = Color.HSBtoRGB( hsb[0], sat, hsb[2]);
}
} else {
for(int y = 0; y<trackRect.height; y++) {
float bri = 1-((float)y)/((float)trackRect.height);
intArray[y] = Color.HSBtoRGB( hsb[0], hsb[1], bri);
}
}
} else {
int[] rgb = colorPicker.getRGB();
if(mode==ColorPicker.RED) {
for(int y = 0; y<trackRect.height; y++) {
int red = 255-(int)(y*255/trackRect.height+.49);
intArray[y] = (red << 16)+(rgb[1] << 8)+(rgb[2]);
}
} else if(mode==ColorPicker.GREEN) {
for(int y = 0; y<trackRect.height; y++) {
int green = 255-(int)(y*255/trackRect.height+.49);
intArray[y] = (rgb[0] << 16)+(green << 8)+(rgb[2]);
}
} else if(mode==ColorPicker.BLUE) {
for(int y = 0; y<trackRect.height; y++) {
int blue = 255-(int)(y*255/trackRect.height+.49);
intArray[y] = (rgb[0] << 16)+(rgb[1] << 8)+(blue);
}
}
}
Graphics2D g2 = (Graphics2D)g;
Rectangle r = new Rectangle(6, trackRect.y, 14, trackRect.height);
if(slider.hasFocus()) {
PlafPaintUtils.paintFocus(g2,r,3);
}
bi.getRaster().setDataElements(0,0,1,trackRect.height,intArray);
TexturePaint p = new TexturePaint(bi,new Rectangle(0,trackRect.y,1,bi.getHeight()));
g2.setPaint(p);
g2.fillRect(r.x,r.y,r.width,r.height);
PlafPaintUtils.drawBevel(g2, r);
}
/**
* Visualize node's location, radio ranges and connections
* @param g2 The graphic context to draw to
*/
private void drawHost(Graphics2D g2) {
Coord loc = node.getLocation();
if (drawCoverage && node.isRadioActive()) {
ArrayList<NetworkInterface> interfaces =
new ArrayList<NetworkInterface>();
interfaces.addAll(node.getInterfaces());
for (NetworkInterface ni : interfaces) {
double range = ni.getTransmitRange();
Ellipse2D.Double coverage;
coverage = new Ellipse2D.Double(scale(loc.getX()-range),
scale(loc.getY()-range), scale(range * 2),
scale(range * 2));
// draw the "range" circle
g2.setColor(rangeColor);
g2.draw(coverage);
}
}
if (drawConnections) {
g2.setColor(conColor);
Coord c1 = node.getLocation();
ArrayList<Connection> conList = new ArrayList<Connection>();
// create a copy to prevent concurrent modification exceptions
conList.addAll(node.getConnections());
for (Connection c : conList) {
DTNHost otherNode = c.getOtherNode(node);
Coord c2;
if (otherNode == null) {
continue; /* disconnected before drawn */
}
c2 = otherNode.getLocation();
g2.drawLine(scale(c1.getX()), scale(c1.getY()),
scale(c2.getX()), scale(c2.getY()));
}
}
/* draw node rectangle */
g2.setColor(hostColor);
g2.drawRect(scale(loc.getX()-1),scale(loc.getY()-1),
scale(2),scale(2));
if (isHighlighted()) {
g2.setColor(highlightedNodeColor);
g2.fillRect(scale(loc.getX()) - 3 ,scale(loc.getY()) - 3, 6, 6);
}
if (drawNodeName) {
g2.setColor(hostNameColor);
// Draw node's address next to it
g2.drawString(node.toString(), scale(loc.getX()),
scale(loc.getY()));
}
}
/**
* Presents the Exceptions if the chart cannot be displayed properly.
*
* @param g2d
* @param ex
*/
private final void showException( Graphics2D g2d, Exception ex )
{
String sWrappedException = ex.getClass( ).getName( );
Throwable th = ex;
while ( ex.getCause( ) != null )
{
ex = (Exception) ex.getCause( );
}
String sException = ex.getClass( ).getName( );
if ( sWrappedException.equals( sException ) )
{
sWrappedException = null;
}
String sMessage = null;
if ( th instanceof BirtException )
{
sMessage = ( (BirtException) th ).getLocalizedMessage( );
}
else
{
sMessage = ex.getMessage( );
}
if ( sMessage == null )
{
sMessage = "<null>";//$NON-NLS-1$
}
StackTraceElement[] stea = ex.getStackTrace( );
Dimension d = getSize( );
Font fo = new Font( "Monospaced", Font.BOLD, 14 );//$NON-NLS-1$
g2d.setFont( fo );
FontMetrics fm = g2d.getFontMetrics( );
g2d.setColor( Color.WHITE );
g2d.fillRect( 20, 20, d.width - 40, d.height - 40 );
g2d.setColor( Color.BLACK );
g2d.drawRect( 20, 20, d.width - 40, d.height - 40 );
g2d.setClip( 20, 20, d.width - 40, d.height - 40 );
int x = 25, y = 20 + fm.getHeight( );
g2d.drawString( "Exception:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Exception:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.RED );
g2d.drawString( sException, x, y );
x = 25;
y += fm.getHeight( );
if ( sWrappedException != null )
{
g2d.setColor( Color.BLACK );
g2d.drawString( "Wrapped In:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Wrapped In:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.RED );
g2d.drawString( sWrappedException, x, y );
x = 25;
y += fm.getHeight( );
}
g2d.setColor( Color.BLACK );
y += 10;
g2d.drawString( "Message:", x, y );//$NON-NLS-1$
x += fm.stringWidth( "Message:" ) + 5;//$NON-NLS-1$
g2d.setColor( Color.BLUE );
g2d.drawString( sMessage, x, y );
x = 25;
y += fm.getHeight( );
g2d.setColor( Color.BLACK );
y += 10;
g2d.drawString( "Trace:", x, y );//$NON-NLS-1$
x = 40;
y += fm.getHeight( );
g2d.setColor( Color.GREEN.darker( ) );
for ( int i = 0; i < stea.length; i++ )
{
g2d.drawString( stea[i].getClassName( ) + ":"//$NON-NLS-1$
+ stea[i].getMethodName( ) + "(...):"//$NON-NLS-1$
+ stea[i].getLineNumber( ), x, y );
x = 40;
y += fm.getHeight( );
}
}
protected void renderWorld() {
Graphics2D g = backImageGraphics2D;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
float backGroundGrey = 25f / 255f;
g.setColor(new Color(backGroundGrey, backGroundGrey, backGroundGrey));
g.fillRect(0, 0, getWidth(), getHeight());
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 渲染行走区
float g4 = 0.4f;
Color triangleColor = new Color(g4, g4, g4);
g.setColor(triangleColor);
for (Triangle triangle : player.getMap().getGraph().getTriangles()) {
g.fill(triangle);
//三角形顶点序号
if (this.isShowTriangleIndex) {
g.setColor(Color.GREEN);
g.drawString(String.valueOf(triangle.index), triangle.center.x, triangle.center.z);
}
//坐标序号
if (this.isShowVectorIndex&&triangle.vectorIndex!=null) {
g.setColor(Color.BLUE);
g.drawString(String.valueOf(triangle.vectorIndex[0]), triangle.a.x, triangle.a.z);
g.drawString(String.valueOf(triangle.vectorIndex[1]), triangle.b.x, triangle.b.z);
g.drawString(String.valueOf(triangle.vectorIndex[2]), triangle.c.x, triangle.c.z);
}
//三角形内随机点
if (isRenderRandomPoints) {
g.setColor(Color.RED);
Vector3 out=new Vector3();
float count = triangle.area()/100;
for(int i=0;i<count;i++) {
triangle.getRandomPoint(out);
g.fill(new Ellipse2D.Double(out.getX() - 3 / 2f, out.getZ() - 3 / 2f, 3, 3));
}
}
g.setColor(triangleColor);
}
//渲染寻路路线
g.setColor(Color.LIGHT_GRAY);
if (player.getPaths().size() > 0) {
Vector3 currentPoint = player.getPos();
for (int j = 0; j < player.getPaths().size(); j++) {
Vector3 nextPoint = player.getPaths().get(j);
g.draw(new Line2D.Double(currentPoint.getX(), currentPoint.getZ(), nextPoint.getX(), nextPoint.getZ()));
float d = 5f;
g.fill(new Ellipse2D.Double(nextPoint.getX() - d / 2f, nextPoint.getZ() - d / 2f, d, d));
currentPoint = nextPoint;
}
}
g.setColor(Color.ORANGE);
g.draw(new Ellipse2D.Double(stop.x, stop.z, 3, 3));
g.setColor(Color.red);
double r = 5;
g.fill(new Ellipse2D.Double(player.getPos().x - r, player.getPos().z - r, 2 * r, 2 * r));
renderOther(g);
}
@Override
public BufferedImage doTransform(BufferedImage src, BufferedImage dest) {
if(gaussianKernelRadius.getValueAsFloat() <= 0.1f) {
// return a black image to avoid exceptions
Graphics2D g = dest.createGraphics();
g.setColor(invert.isChecked() ? Color.WHITE : Color.BLACK);
g.fillRect(0, 0, dest.getWidth(), dest.getHeight());
g.dispose();
return dest;
}
long estimatedMemoryMB = estimateNeededMemoryMB(src);
System.gc(); // needed for the memory estimation
var memoryInfo = new MemoryInfo();
long availableMemoryMB = memoryInfo.getAvailableMemoryMB();
if (estimatedMemoryMB > availableMemoryMB) {
showNotEnoughMemoryDialog(estimatedMemoryMB, availableMemoryMB);
dest = src;
return dest;
}
// do not cache this object because it holds a lot of memory!
var detector = new CannyEdgeDetector();
detector.setLowThreshold(lowThreshold.getPercentageValF());
detector.setHighThreshold(highThreshold.getPercentageValF());
detector.setContrastNormalized(contrastNormalized.isChecked());
detector.setGaussianKernelRadius(gaussianKernelRadius.getValueAsFloat());
detector.setGaussianKernelWidth(gaussianKernelWidth.getValue());
detector.setSourceImage(src);
detector.process();
dest = detector.getEdgesImage();
if (invert.isChecked()) {
Invert.quickInvert(dest);
}
return dest;
}
private void render(Graphics2D g) {
g.setColor(Color.red);
g.fillRect(0, 0, w, h);
}