- 追加された行はこの色です。
- 削除された行はこの色です。
#topicpath
----
GUIプログラムを使っていると、アイコンなどイメージデータを取り扱うことになりますが、SWTのイメージデータウィジェットである[[org.eclipse.swt.graphics.Image:http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/graphics/Image.html]]をばんばん作成するとクラスOSのリソースを結構消費する(らしい)のと、適切にdisposeしなくてはいけないなど、結構面倒です。
そこで画像データはだれかが一括管理すれば効率がよいわけですが、それをしてくれるクラスが
org.eclipse.jface.resource.ImageDescriptor
org.eclipse.jface.resource.ImageRegistry
です。
[[ImageDescriptor:http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/resource/ImageDescriptor.html]]は、ひとつの画像データを使い回すためのsingletonのようなモノみたいで((たぶん一つの画像データに対して一つしか作成されないのだと思われる))、
ImageDescriptor#createImage()
でImageクラスを取得します。
[[ImageRegistry:http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/resource/ImageRegistry.html]]はImageDescriptorを管理するためのHashMapを持つクラスで、
public void put(String key, ImageDescriptor descriptor);
public ImageDescriptor getDescriptor(String key);
でImageDescriptor の登録、取得を行います。
***プラグイン開発ではどうやるのか [#tcac85da]
さて、画像を取り扱うクラスはわかりましたが、プラグインのどのメソッドで登録されて、どのタイミングで取り出されているか、きっと一般的な取り扱いがあるだろうなあとおもっていろんなプラグインとかのソースを見てみたんですけど、だいたい以下のようなやり方でイメージデータを扱っているようです。
+プラグインディレクトリ/iconsというディレクトリを作成し、その中にgifファイルなどイメージデータをおいておく
+プラグインクラスで
public static final String IMG_VERTICAL = "vertical";
などとキー名を決めておく
+プラグインクラスでAbstractUIPlugin#initializeImageRegistry(ImageRegistry)をオーバライド
+HogePlugin.getDefault().getImageRegistry().getDescriptor(HogePlugin.IMG_VERTICAL)でImageDescriptorを取得
具体的にはこんな感じになっていました。
public class HogetPlugin extends AbstractUIPlugin {
public static final String IMG_VERTICAL = "vertical";
//ほかにもキー値を作っておく
protected void initializeImageRegistry(ImageRegistry registry) {
registerImage(registry, IMG_VERTICAL, "th_vertical.gif");
// ..他にも登録
}
private void registerImage(ImageRegistry registry, String key,String fileName){
try {
IPath path = new Path("icons/" + fileName);
URL url = find(path);
if (url != null) {
ImageDescriptor desc = ImageDescriptor.createFromURL(url);
registry.put(key, desc);
}
} catch (Exception e) {
e.printStackTrace();
}
}
これで icons/th_vertical.gif のImageDescriptorが
HogePlugin.getDefault().getImageRegistry().getDescriptor(HogePlugin.IMG_VERTICAL)
で取得可能です。
このようにしておいて、''ImageDescriptorをImageRegistryから取得して、そのImageDescriptorからImageを作成する''としておけばImageのdisposeはEclipse側がやってくれるようです。
----
この記事は
#vote(おもしろかった[3],そうでもない[0])
#vote(おもしろかった[4],そうでもない[0])
#comment
#topicpath
SIZE(10){現在のアクセス:&counter;}