How can I display and resize an image in SWT? The image to be displayed in the SWT cannot be changed. For example, we use backgroundimage. But sometimes I need to automatically adapt the image we want to display to a certain proportion of the area we want to display. This is what we need to do with drawing.
Each control has a paintcontral event. We can use its events to draw images.
Image has two methods to obtain image files:
Final display = display. getdefault ();
Image image%swtresourcemanager.getimage(aaaa.class,#showpicture.jpg ");
// Aaaaas is the name of the front file. showpicture.jpg is an image in the same directory as the current file.
// Relative paths supported for such issuance
// SWT does not support real-time updates of files in the project at runtime.
Image image = new image (display, "c: \ showpicture.jpg ");
// When using this method, you need to place the display to a location that can be referenced. relative paths are not supported.
For example, we now have a label and a button. click the button to replace the labeld image.
Image image = new image (display, "c: \ a.jpg ");
Label. addpaintlistener (New paintlistener (){
Public void paintcontral (paintevent e ){
Final rectangle bounds = image. getbounds ();
Int picwidth = bounds. width; // Image Width
Int picheight = bounds. height; // The Image Height.
Double H = 200; // label height
Double W = 150; // label width
Double ratio = 1; // scaling ratio
Double R1 = H/picheight;
Double r2 = W/picwidth;
Ratio = math. Min (R1, R2 );
E. gc. drawimage (image, 0, 0, picwidth, picheight, 0, 0,
(INT) (picwidth * ratio), (INT) (picheight * Ratio ));
// Parameter 1: Image
// 2 and 3: The coordinates of the image relative to the area to be displayed, in the upper left corner
// 4,5: image width and height
// 6, 7: The range of the image to be displayed. The value of the complete image to be displayed is 0.
// 8, 9: the width and height of the image to be displayed
}
});
We only need to write in the event of clicking the button:
Image = new image(display, B .jpg ");
Label. redraw ();
You can change the image when you click the button.