下面列出了怎么用java.awt.AlphaComposite的API类实例代码及写法,或者点击链接到github查看源代码。
private static void draw(Shape clip, Shape to, Image vi, BufferedImage bi,
int scale) {
Graphics2D big = bi.createGraphics();
big.setComposite(AlphaComposite.Src);
big.setClip(clip);
Rectangle toBounds = to.getBounds();
int x1 = toBounds.x;
int y1 = toBounds.y;
int x2 = x1 + toBounds.width;
int y2 = y1 + toBounds.height;
big.drawImage(vi, x1, y1, x2, y2, 0, 0, toBounds.width / scale,
toBounds.height / scale, null);
big.dispose();
vi.flush();
}
public void paint(Graphics g) {
// Create an image for the button graphics if necessary
if (buttonImage == null || buttonImage.getWidth() != getWidth() ||
buttonImage.getHeight() != getHeight()) {
buttonImage = getGraphicsConfiguration().
createCompatibleImage(getWidth(), getHeight());
}
Graphics gButton = buttonImage.getGraphics();
gButton.setClip(g.getClip());
// Have the superclass render the button for us
super.paint(gButton);
// Make the graphics object sent to this paint() method translucent
Graphics2D g2d = (Graphics2D)g;
AlphaComposite newComposite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f);
g2d.setComposite(newComposite);
// Copy the button's image to the destination graphics, translucently
g2d.drawImage(buttonImage, 0, 0, null);
}
/**
* Draws the background image (if there is one) aligned within the
* specified area.
*
* @param g2 the graphics device.
* @param area the area.
*
* @see #getBackgroundImage()
* @see #getBackgroundImageAlignment()
* @see #getBackgroundImageAlpha()
*/
public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {
if (this.backgroundImage == null) {
return; // nothing to do
}
Composite savedComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
this.backgroundImageAlpha));
Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,
this.backgroundImage.getWidth(null),
this.backgroundImage.getHeight(null));
Align.align(dest, area, this.backgroundImageAlignment);
Shape savedClip = g2.getClip();
g2.clip(area);
g2.drawImage(this.backgroundImage, (int) dest.getX(),
(int) dest.getY(), (int) dest.getWidth() + 1,
(int) dest.getHeight() + 1, null);
g2.setClip(savedClip);
g2.setComposite(savedComposite);
}
private static long test(Image bi, Image vi, AffineTransform atfm) {
final Polygon p = new Polygon();
p.addPoint(0, 0);
p.addPoint(SIZE, 0);
p.addPoint(0, SIZE);
p.addPoint(SIZE, SIZE);
p.addPoint(0, 0);
Graphics2D g2d = (Graphics2D) vi.getGraphics();
g2d.clip(p);
g2d.transform(atfm);
g2d.setComposite(AlphaComposite.SrcOver);
final long start = System.nanoTime();
g2d.drawImage(bi, 0, 0, null);
final long time = System.nanoTime() - start;
g2d.dispose();
return time;
}
/**
* Method contributed by Alexej Suchov
* @see Graphics2D#setComposite(Composite)
*/
public void setComposite(Composite comp) {
if (comp instanceof AlphaComposite) {
AlphaComposite composite = (AlphaComposite) comp;
if (composite.getRule() == 3) {
alpha = composite.getAlpha();
this.composite = composite;
if (realPaint != null && (realPaint instanceof Color)) {
Color c = (Color) realPaint;
paint = new Color(c.getRed(), c.getGreen(), c.getBlue(),
(int) (c.getAlpha() * alpha));
}
return;
}
}
this.composite = comp;
alpha = 1.0F;
}
/**
* Record information about drawing done
* with the supplied <code>Composite</code>.
*/
private void checkAlpha(Composite composite) {
if (composite instanceof AlphaComposite) {
AlphaComposite alphaComposite = (AlphaComposite) composite;
float alpha = alphaComposite.getAlpha();
int rule = alphaComposite.getRule();
if (alpha != 1.0
|| (rule != AlphaComposite.SRC
&& rule != AlphaComposite.SRC_OVER)) {
mHasCompositing = true;
}
} else {
mHasCompositing = true;
}
}
@Override
public void paintData(final Graphics2D g, final Rectangle srcRect,
final Tree<Float> tree, final AffineTransform to_screen, final Color cc,
final Layer active_layer) {
if (null == this.parent) return; // doing it here for less total cost
if (0 == this.r && 0 == parent.getData()) return;
// Two transformations, but it's only 4 points each and it's necessary
//final Polygon segment = getSegment();
//if (!tree.at.createTransformedShape(segment).intersects(srcRect)) return Node.FALSE;
//final Shape shape = to_screen.createTransformedShape(segment);
final Shape shape = to_screen.createTransformedShape(getSegment());
final Composite c = g.getComposite();
final float alpha = tree.getAlpha();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha > 0.4f ? 0.4f : alpha));
g.setColor(cc);
g.fill(shape);
g.setComposite(c);
g.draw(shape); // in Tree's composite mode (such as an alpha)
}
private void setComposite(Composite comp, int flags) {
// assert rq.lock.isHeldByCurrentThread();
if (comp instanceof AlphaComposite) {
AlphaComposite ac = (AlphaComposite)comp;
rq.ensureCapacity(16);
buf.putInt(SET_ALPHA_COMPOSITE);
buf.putInt(ac.getRule());
buf.putFloat(ac.getAlpha());
buf.putInt(flags);
} else if (comp instanceof XORComposite) {
int xorPixel = ((XORComposite)comp).getXorPixel();
rq.ensureCapacity(8);
buf.putInt(SET_XOR_COMPOSITE);
buf.putInt(xorPixel);
} else {
throw new InternalError("not yet implemented");
}
}
/**
* Creates a new instance of HighlightedButton
*/
public HighlightedButton(String label) {
super(label);
// Get the Graphics for the image
Graphics2D g2d = highlight.createGraphics();
// Erase the image with a transparent background
g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
g2d.setComposite(AlphaComposite.SrcOver);
// Draw the highlight
Point2D center = new Point2D.Float((float)HIGHLIGHT_SIZE / 2.0f,
(float)HIGHLIGHT_SIZE / 2.0f);
float radius = (float)HIGHLIGHT_SIZE / 2.0f;
float[] dist = {0.0f, .85f};
Color[] colors = {Color.white, new Color(255, 255, 255, 0)};
RadialGradientPaint paint = new RadialGradientPaint(center, radius,
dist, colors);
g2d.setPaint(paint);
g2d.fillOval(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
g2d.dispose();
}
public static BufferedImage createDropShadow(BufferedImage image,
int size) {
BufferedImage shadow = new BufferedImage(
image.getWidth() + 4 * size,
image.getHeight() + 4 * size,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = shadow.createGraphics();
g2.drawImage(image, size * 2, size * 2, null);
g2.setComposite(AlphaComposite.SrcIn);
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, shadow.getWidth(), shadow.getHeight());
g2.dispose();
shadow = getGaussianBlurFilter(size, true).filter(shadow, null);
shadow = getGaussianBlurFilter(size, false).filter(shadow, null);
return shadow;
}
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);
}
/**
* Creates a new instance of DefaultPolarItemRenderer
*/
public DefaultPolarItemRenderer() {
this.seriesFilled = new BooleanList();
this.drawOutlineWhenFilled = true;
this.fillComposite = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f);
this.useFillPaint = false; // use item paint for fills by default
this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
this.shapesVisible = true;
this.connectFirstAndLastPoint = true;
this.toolTipGeneratorList = new ObjectList();
this.urlGenerator = null;
this.legendItemToolTipGenerator = null;
this.legendItemURLGenerator = null;
}
private void createAnimation(ImageIds animationImageId, ImageIds imageId, int numberOfFrames) {
List<Image> images = new ArrayList<>();
for(int i=0; i<numberOfFrames; i++) {
BufferedImage newImage = new BufferedImage(48, 48, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) newImage.getGraphics();
Image image = idToImages.get(imageId).get(0);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f * i));
g2.drawImage(image, 0, 0, null);
g2.dispose();
images.add(newImage);
}
idToImages.put(animationImageId, images);
}
/**
* Draws the background image (if there is one) aligned within the
* specified area.
*
* @param g2 the graphics device.
* @param area the area.
*
* @see #getBackgroundImage()
* @see #getBackgroundImageAlignment()
* @see #getBackgroundImageAlpha()
*/
public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {
if (this.backgroundImage == null) {
return; // nothing to do
}
Composite savedComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
this.backgroundImageAlpha));
Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,
this.backgroundImage.getWidth(null),
this.backgroundImage.getHeight(null));
Align.align(dest, area, this.backgroundImageAlignment);
Shape savedClip = g2.getClip();
g2.clip(area);
g2.drawImage(this.backgroundImage, (int) dest.getX(),
(int) dest.getY(), (int) dest.getWidth() + 1,
(int) dest.getHeight() + 1, null);
g2.setClip(savedClip);
g2.setComposite(savedComposite);
}
public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) {
g.setColor(getColor(colorA));
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, get(opacity) / 255.0f));
RoundRectangle2D rr = new RoundRectangle2D.Float(x, y, width - 1, height - 1, get(arcWidth), get(arcHeight));
g2d.setPaint(new GradientPaint(x + width / 2, y, getColor(colorA), x + width / 2, y + height, getColor(colorB)));
g2d.fill(rr);
if(get(thickness) > 0) {
g2d.setPaint(new GradientPaint(x + width / 2, y, getColor(colorC), x + width / 2, y + height, getColor(colorD)));
g2d.setStroke(new BasicStroke(get(thickness)));
g2d.draw(rr);
}
}
/**
* Record information about drawing done
* with the supplied <code>Composite</code>.
*/
private void checkAlpha(Composite composite) {
if (composite instanceof AlphaComposite) {
AlphaComposite alphaComposite = (AlphaComposite) composite;
float alpha = alphaComposite.getAlpha();
int rule = alphaComposite.getRule();
if (alpha != 1.0
|| (rule != AlphaComposite.SRC
&& rule != AlphaComposite.SRC_OVER)) {
mHasCompositing = true;
}
} else {
mHasCompositing = true;
}
}
public void modifyTest(TestEnvironment env) {
int size = env.getIntValue(sizeList);
Image src = tsit.getImage(env, size, size);
Graphics g = src.getGraphics();
if (hasGraphics2D) {
((Graphics2D) g).setComposite(AlphaComposite.Src);
}
if (size == 1) {
g.setColor(colorsets[transparency][4]);
g.fillRect(0, 0, 1, 1);
} else {
int mid = size/2;
g.setColor(colorsets[transparency][0]);
g.fillRect(0, 0, mid, mid);
g.setColor(colorsets[transparency][1]);
g.fillRect(mid, 0, size-mid, mid);
g.setColor(colorsets[transparency][2]);
g.fillRect(0, mid, mid, size-mid);
g.setColor(colorsets[transparency][3]);
g.fillRect(mid, mid, size-mid, size-mid);
}
g.dispose();
env.setSrcImage(src);
}
/**
* Initialize the common resources.
* @param rl the resource locator
* @return this
*/
public CommonGFX load(ResourceLocator rl) {
GFXLoader.loadResources(this, rl);
int[] disabled = { 0xFF000000, 0xFF000000, 0, 0, 0xFF000000, 0, 0, 0, 0 };
disabledPattern = new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB);
disabledPattern.setRGB(0, 0, 3, 3, disabled, 0, 3);
achievementGrayed = new BufferedImage(achievement.getWidth(), achievement.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = achievementGrayed.createGraphics();
g2.drawImage(achievement, 0, 0, null);
g2.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, achievement.getWidth(), achievement.getHeight());
g2.dispose();
mediumButton = new GenericMediumButton("/hu/openig/gfx/button_medium.png");
mediumButtonPressed = new GenericMediumButton("/hu/openig/gfx/button_medium_pressed.png");
return this;
}
private static long test(Image bi, Image vi, AffineTransform atfm) {
final Polygon p = new Polygon();
p.addPoint(0, 0);
p.addPoint(SIZE, 0);
p.addPoint(0, SIZE);
p.addPoint(SIZE, SIZE);
p.addPoint(0, 0);
Graphics2D g2d = (Graphics2D) vi.getGraphics();
g2d.clip(p);
g2d.transform(atfm);
g2d.setComposite(AlphaComposite.SrcOver);
final long start = System.nanoTime();
g2d.drawImage(bi, 0, 0, null);
final long time = System.nanoTime() - start;
g2d.dispose();
return time;
}
/**
* Creates a blend composite
*
* @param blendMode Desired blend mode
* @param constantAlpha Constant alpha, must be in the inclusive range
* [0.0...1.0] or it will be clipped.
* @return a blend composite.
*/
public static Composite getInstance(BlendMode blendMode, float constantAlpha)
{
if (constantAlpha < 0)
{
LOG.warn("using 0 instead of incorrect Alpha " + constantAlpha);
constantAlpha = 0;
}
else if (constantAlpha > 1)
{
LOG.warn("using 1 instead of incorrect Alpha " + constantAlpha);
constantAlpha = 1;
}
if (blendMode == BlendMode.NORMAL)
{
return AlphaComposite.getInstance(AlphaComposite.SRC_OVER, constantAlpha);
}
else
{
return new BlendComposite(blendMode, constantAlpha);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
// get width and height
final int width = getWidth();
final int height = getHeight();
// Draw 12 lines around the center point in a circle
int lineLength = Math.min(width, height) / 5;
int lineWidth = lineLength / 4;
int cx = width / 2;
int cy = height / 2;
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.setPaint(JBColor.black);
g2.rotate(Math.PI * rotationAngle / 180, cx, cy);
for (int i = 0; i < 12; i++) {
g2.drawLine(cx + lineLength, cy, cx + lineLength * 2, cy);
g2.rotate(-Math.PI / 6, cx, cy);
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, ((11 - i) / 12.0f) * (2.0f / 3.0f)));
}
g2.dispose();
}
/**
* Creates a MockComponent that resembles the argument component.
* <P>
* Note this method will traverse c and its subcomponents and may
* temporarily change properties of inner components: such as the focused
* state, the visibility, etc.
* <P>
* The goal is of this component is not to mirror the exact state of a
* component, but rather to provide a sample image of this component in its
* plain, unmodified, unused state.
*
* @param c
*/
public MockComponent(JComponent c) {
Dimension preferredSize = c.getPreferredSize();
Dimension currentSize = c.getSize();
Dimension d = new Dimension(Math.max(preferredSize.width,
currentSize.width), Math.max(preferredSize.height,
currentSize.height));
if (currentSize.width == 0 || currentSize.height == 0) {
// if the component isn't visible yet
c.setSize(d);
c.doLayout();
}
storeState(c);
image = new BufferedImage(d.width, d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, d.width, d.height);
g.setComposite(AlphaComposite.SrcOver);
c.paint(g);
g.dispose();
setPreferredSize(d);
setMinimumSize(d);
setMaximumSize(d);
setOpaque(c.isOpaque());
setName(c.getName());
setToolTipText(c.getToolTipText());
restoreState(c);
}
/**
* 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();
}
/**
* Return a CompositeType object for the specified AlphaComposite
* rule.
*/
public static CompositeType forAlphaComposite(AlphaComposite ac) {
switch (ac.getRule()) {
case AlphaComposite.CLEAR:
return Clear;
case AlphaComposite.SRC:
if (ac.getAlpha() >= 1.0f) {
return SrcNoEa;
} else {
return Src;
}
case AlphaComposite.DST:
return Dst;
case AlphaComposite.SRC_OVER:
if (ac.getAlpha() >= 1.0f) {
return SrcOverNoEa;
} else {
return SrcOver;
}
case AlphaComposite.DST_OVER:
return DstOver;
case AlphaComposite.SRC_IN:
return SrcIn;
case AlphaComposite.DST_IN:
return DstIn;
case AlphaComposite.SRC_OUT:
return SrcOut;
case AlphaComposite.DST_OUT:
return DstOut;
case AlphaComposite.SRC_ATOP:
return SrcAtop;
case AlphaComposite.DST_ATOP:
return DstAtop;
case AlphaComposite.XOR:
return AlphaXor;
default:
throw new InternalError("Unrecognized alpha rule");
}
}
/**
* Sets the current composite. This implementation currently supports
* only the {@link AlphaComposite} class.
*
* @param comp the composite (<code>null</code> not permitted).
*/
public void setComposite(Composite comp) {
if (comp == null) {
throw new IllegalArgumentException("Null 'comp' argument.");
}
this.composite = comp;
if (comp instanceof AlphaComposite) {
AlphaComposite acomp = (AlphaComposite) comp;
int alpha = (int) (acomp.getAlpha() * 0xFF);
this.gc.setAlpha(alpha);
}
}
public SunCompositeContext(AlphaComposite ac,
ColorModel s, ColorModel d)
{
if (s == null) {
throw new NullPointerException("Source color model cannot be null");
}
if (d == null) {
throw new NullPointerException("Destination color model cannot be null");
}
srcCM = s;
dstCM = d;
this.composite = ac;
this.comptype = CompositeType.forAlphaComposite(ac);
}
private static void fill(final Image image) {
final Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setComposite(AlphaComposite.Src);
for (int i = 0; i < image.getHeight(null); ++i) {
graphics.setColor(new Color(i, 0, 0));
graphics.fillRect(0, i, image.getWidth(null), 1);
}
graphics.dispose();
}
public void setParam(BrowserContext c, Object o, String v) throws ParameterException {
Style s = (Style) o;
float transparency = 0.0f;
if (v != null) {
try {
transparency = Float.parseFloat(v);
} catch (NumberFormatException n) {
throw new ParameterException("Not a valid transparency value "+v);
}
if (transparency < 0.0f || transparency > 1.0f) {
throw new ParameterException("Not a valid transparency value "+transparency);
}
}
s.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
}
@Override
public void BlitBg(SurfaceData srcData,
SurfaceData dstData,
Composite comp,
Region clip,
int bgArgb,
int srcx, int srcy,
int dstx, int dsty,
int width, int height)
{
ColorModel dstModel = dstData.getColorModel();
boolean bgHasAlpha = (bgArgb >>> 24) != 0xff;
if (!dstModel.hasAlpha() && bgHasAlpha) {
dstModel = ColorModel.getRGBdefault();
}
WritableRaster wr =
dstModel.createCompatibleWritableRaster(width, height);
boolean isPremult = dstModel.isAlphaPremultiplied();
BufferedImage bimg =
new BufferedImage(dstModel, wr, isPremult, null);
SurfaceData tmpData = BufImgSurfaceData.createData(bimg);
Color bgColor = new Color(bgArgb, bgHasAlpha);
SunGraphics2D sg2d = new SunGraphics2D(tmpData, bgColor, bgColor,
defaultFont);
FillRect fillop = FillRect.locate(SurfaceType.AnyColor,
CompositeType.SrcNoEa,
tmpData.getSurfaceType());
Blit combineop = Blit.getFromCache(srcData.getSurfaceType(),
CompositeType.SrcOverNoEa,
tmpData.getSurfaceType());
Blit blitop = Blit.getFromCache(tmpData.getSurfaceType(), compositeType,
dstData.getSurfaceType());
fillop.FillRect(sg2d, tmpData, 0, 0, width, height);
combineop.Blit(srcData, tmpData, AlphaComposite.SrcOver, null,
srcx, srcy, 0, 0, width, height);
blitop.Blit(tmpData, dstData, comp, clip,
0, 0, dstx, dsty, width, height);
}
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;
}