您的位置:首页 > 其它

如何做RCP里的图片资源管理

2012-04-12 14:21 239 查看
这里我写了一中读取资源图片管理的方法,这个方法的好处就是,加载过的图片把它放在MAP里,下次再用的时候不用重新加载。

1.在这个plugin的最顶层目录下创建 icons文件,然后把图片放在这个文件夹里。

2.在这个plugin 里的Activator(默认是这个类名,一般自己会改成其他和PLUGIN相关的名字)里写static方法,这方法能根据图片所在地路径名字取得图片

public class Activator extends AbstractUIPlugin {
......
public static Image getImage(String path) {
return getImage(getDefault().getImageRegistry(), path.toString());
}
public static Image getImage(ImageRegistry registry, String path){
try{
Image img= registry.get(path);
if(img==null){
ImageDescriptor desc= Activator.imageDescriptorFromPlugin(Activator.class.getPackage().getName(), path);
registry.put(path, desc);
img= registry.get(path);
}
return img;
}catch(MissingResourceException e){
e.printStackTrace();
}
return null;

}
......
}


注意图片路径可以为/icons/xxx.gif ,也可以为icons/xxx.gif. 因为内部代码会自动转化。如果不用这种办法取得资源路径,那么只能用/icons/xxx.gif绝对路径。O YEA~

3.然后就可以在别的类里根据图片路径读出IMG。

例如。

class ImgShows{
......
public Img getImg(String path){
Image img=Activator.getImage(path);

}
......

}


4.如果想把这个图放在CLabel里。最好这么写。这里我用formLayout.

Image img=Activator.getImage(imgPath.toString());
CLabel icon = new CLabel(headComposite, SWT.NONE);
icon.setBackground(img);
final FormData iconFormData = new FormData();
iconFormData.top = new FormAttachment(LAYOUT.ZERO_PERCENT, LAYOUT.MARGIN_TOP_COMPOSITE);
iconFormData.left = new FormAttachment(LAYOUT.ZERO_PERCENT, LAYOUT.MARGIN_LEFT_COMPOSITE);
iconFormData.width=img.getBounds().width;
iconFormData.height=img.getBounds().height;
icon.setLayoutData(iconFormData);


这样的图大小工整。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: