package com.fr.base.svg; import javax.swing.Icon; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; /** * SVG转化而来的Icon * @author Yvan * @version 10.0 * Created by Yvan on 2020/12/17 */ public class SVGIcon implements Icon { private BufferedImage image; private static final boolean HI_DPI_SURPORT = SystemScaleUtils.isJreHiDPIEnabled(); public static final float SYSTEM_SCALE = SystemScaleUtils.sysScale(); private static final String ICON_PREFIX = "/"; public SVGIcon(BufferedImage image) { this.image = image; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { if (HI_DPI_SURPORT) { Graphics2D graphics = (Graphics2D) g.create(x, y, image.getWidth(null), image.getHeight(null)); float scale = SYSTEM_SCALE; graphics.scale(1 / scale, 1 / scale); graphics.drawImage(image, 0, 0, null); graphics.scale(1.0D, 1.0D); graphics.dispose(); } else { g.drawImage(image, x, y, null); } } @Override public int getIconWidth() { return HI_DPI_SURPORT ? (int) (image.getWidth() / SYSTEM_SCALE) : image.getWidth(); } @Override public int getIconHeight() { return HI_DPI_SURPORT ? (int) (image.getHeight() / SYSTEM_SCALE) : image.getHeight(); } /** * 外界读取高清图标,默认尺寸为16*16 * @param url * @return */ public static Icon readSVGIcon(String url) { if (!url.startsWith(ICON_PREFIX)) { url = ICON_PREFIX + url; } return new SVGIcon((BufferedImage) SVGLoader.load(url)); } /** * 读取指定尺寸的图标 * @param url 资源路径 * @param width 宽度 * @param height 高度 * @return */ public static Icon readSVGIcon(String url, float width, float height) { if (!url.startsWith(ICON_PREFIX)) { url = ICON_PREFIX + url; } return new SVGIcon((BufferedImage) SVGLoader.load(url, width, height)); } }