java polygon 用法_Java Graphics.fillPolygon:如何渲染右边和底边?

我喜欢@HFOE所示的ImageIcon的便利性,但这种变化可能会让你更容易看到发生的事情。来自Graphics API,

Operations that draw the outline of a figure operate by traversing an

infinitely thin path between pixels with a pixel-sized pen that hangs

down and to the right of the anchor point on the path. Operations that

fill a figure operate by filling the interior of that infinitely thin

path.

相比之下,Graphics2D必须遵循更复杂的抗锯齿规则,这允许它“在线外绘制”。

fkpxG.png

import java.awt.Color;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.GridLayout;

import java.awt.RenderingHints;

import java.awt.image.BufferedImage;

import javax.swing.JFrame;

import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/7701097 */

public class PixelView extends JPanel {

private static final int SIZE = 20;

private static final int SCALE = 16;

private BufferedImage img;

public PixelView(Color fill) {

this.setBackground(Color.white);

this.setPreferredSize(new Dimension(SCALE * SIZE, SCALE * SIZE));

img = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2 = img.createGraphics();

int[] xPoints = {SIZE / 3, (2 * SIZE) / 3, SIZE / 3};

int[] yPoints = {0, SIZE / 2, SIZE};

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setColor(Color.green);

g2.drawLine(0, SIZE - 1, SIZE, SIZE - 1);

g2.drawLine(0, 0, SIZE, 0);

g2.drawLine(SIZE / 3, 0, SIZE / 3, SIZE);

g2.drawLine((2 * SIZE / 3), 0, (2 * SIZE / 3), SIZE);

g2.setColor(Color.black);

g2.drawPolygon(xPoints, yPoints, xPoints.length);

g2.setColor(fill);

g2.fillPolygon(xPoints, yPoints, xPoints.length);

g2.dispose();

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(img, 0, 0, getWidth(), getHeight(), null);

}

private static void display() {

JFrame f = new JFrame("PixelView");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new GridLayout(1, 0));

f.add(new PixelView(Color.black));

f.add(new PixelView(Color.red));

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

display();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值