-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImagePanel.java
More file actions
78 lines (65 loc) · 1.69 KB
/
ImagePanel.java
File metadata and controls
78 lines (65 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package board;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
/**
* ImagePanel is JPanel variant for displaying BufferedImage
* <p>
* to maintain alpha channel in image, ImagePanel is transparent, by default.
*
* @see JPanel
* @see BufferedImage
* @author LeNerd
* @since 2018-05-23
*/
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1241885397633460571L;
BufferedImage image;
public ImagePanel() {
setOpaque(false);
}
/**
* set Image to draw
*
* @param image
* image to set.
*/
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* get current Image
*
* @return BufferedImage
*/
public BufferedImage getImage() {
return image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
/*
* inform render to use bilinear interpolation
*/
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
if (image != null) {
/*
* if image is set, draw to fill.
* with aspect ratio
*/
float wr = (float)getWidth() / (float)image.getWidth();
float hr = (float)getHeight() / (float)image.getHeight();
float r = Math.min(wr, hr);
int w = (int)(image.getWidth()*r);
int h = (int)(image.getHeight()*r);
g.drawImage(image, (getWidth()-w)/2,(getHeight()-h)/2,w,h, this);
}
}
}