Demo: support dark SVG icons

This commit is contained in:
Karl Tauber
2019-09-18 13:20:07 +02:00
parent c4e0ef198f
commit 91f304054e
10 changed files with 92 additions and 1 deletions

View File

@@ -22,7 +22,10 @@ import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import com.formdev.flatlaf.FlatDarkLaf;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.UIScale;
import com.kitfox.svg.app.beans.SVGIcon;
@@ -33,31 +36,57 @@ import com.kitfox.svg.app.beans.SVGIcon;
public class ScaledSVGIcon
extends ImageIcon
{
private final String name;
private final SVGIcon svgIcon;
private boolean dark;
public ScaledSVGIcon( String name ) {
this.name = name;
svgIcon = new SVGIcon();
svgIcon.setAntiAlias( true );
}
private void update() {
if( dark == isDarkLaf() && svgIcon.getSvgURI() != null )
return;
dark = isDarkLaf();
URL url = getIconURL( name, dark );
if( url == null & dark )
url = getIconURL( name, false );
try {
svgIcon.setSvgURI( getClass().getResource( name ).toURI() );
svgIcon.setSvgURI( url.toURI() );
} catch( URISyntaxException ex ) {
ex.printStackTrace();
}
}
private URL getIconURL( String name, boolean dark ) {
if( dark ) {
int dotIndex = name.lastIndexOf( '.' );
name = name.substring( 0, dotIndex ) + "_dark" + name.substring( dotIndex );
}
return getClass().getResource( name );
}
@Override
public int getIconWidth() {
update();
return UIScale.scale( svgIcon.getIconWidth() );
}
@Override
public int getIconHeight() {
update();
return UIScale.scale( svgIcon.getIconHeight() );
}
@Override
public void paintIcon( Component c, Graphics g, int x, int y ) {
update();
Graphics2D g2 = (Graphics2D) g.create();
try {
FlatUIUtils.setRenderingHints( g2 );
@@ -73,6 +102,8 @@ public class ScaledSVGIcon
@Override
public Image getImage() {
update();
BufferedImage image = new BufferedImage( getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB );
Graphics2D g = image.createGraphics();
try {
@@ -82,4 +113,22 @@ public class ScaledSVGIcon
}
return image;
}
private static Boolean darkLaf;
private static boolean isDarkLaf() {
if( darkLaf == null ) {
lafChanged();
UIManager.addPropertyChangeListener( e -> {
lafChanged();
} );
}
return darkLaf;
}
private static void lafChanged() {
darkLaf = (UIManager.getLookAndFeel() instanceof FlatDarkLaf);
}
}