2014년 2월 9일 일요일

SWT - Image 넣기




Image 넣기


SWT에서 이미지를 보여주려면, Image 생성자 Image(Device, String) 를 사용합니다. 첫 번째 인자로 Device는 Display를, 두 번째 인자는 이미지 파일의 경로명을 입력합니다.

이미지 파일을 현재 클래스의 동일한 디렉토리에 있는 이미지를 사용하려면, InputStream을 생성하여 해당 클래스의 getResourceAsStream() 메서드를 호출하여 Image 생성자의 두 번째 인자로 사용할 수 있습니다.

InputStream is = getClass().getResourceAsStream("FlagGIF.gif");
Image image = new Image(Display, is);


아래의 예제코드는 InputStream을 사용하여 ImageData 객체를 생성하고, 프로그램이 PaintEvent가 발생하면, paintControl() 을 호출하여 Image 객체를 생성하여 GC에 그려서 보여주는 코드입니다.




예제코드

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
package com.swtjface.Ch7;
 
import java.io.InputStream;
 
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Composite;
 
public class ImageComposite extends Composite {
 public ImageComposite(Composite parent){
  super(parent, SWT.NONE);
  parent.setSize(320, 190);
 
   //1. 파일로 부터 ImageData 객체 생성
  InputStream is = getClass().getResourceAsStream("FlagGIF.gif");
  final ImageData imageData = new ImageData(is).scaledTo(220, 120);
  
  //2. PaintEvent 발생
  this.addPaintListener(new PaintListener() {
   
   //2-1. paintControl 호출
   @Override
   public void paintControl(PaintEvent pe) {
    GC gc = pe.gc;
    //ImageData로부터 Image 생성
    Image image = new Image(pe.display, imageData);
    gc.drawImage(image, 20, 20);
    gc.drawText("The image height is : " + imageData.height + "pixels.", 330,30);
    gc.drawText("The image width is : " + imageData.width + "pixels.", 330,70);
    gc.drawText("The image depth is : " + imageData.depth + "pixels.", 330,110);
    image.dispose();
   }
  });
 }
}
 


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
package com.swtjface.Ch7;
 
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
 
public class Test extends ApplicationWindow {
 public Test() {
  super(null);
 }
 
 protected Control createContents(Composite parent) {
  ImageComposite composite = new ImageComposite(parent);
  
  getShell().setText("Widget Window");
  parent.setSize(600, 250);
  return parent;
 }
 
 public static void main(String[] args) {
  Test tc = new Test();
  tc.setBlockOnOpen(true);
  tc.open();
  Display.getCurrent().dispose();
 }
 
}



실행결과




참고서적 : SWT/JFace in Action



댓글 없음:

댓글 쓰기