---
title: "如何做RCP里的图片资源管理"
author: "dmwdmc"
date: "2010-04-12T14:38:52Z"
tags: []
categories: ["企业架构"]
slug: "rcp"
draft: false
lastmod: "2010-04-13T13:44:44Z"
id: 641850
url: "https://dmwdmc.iteye.com/blog/641850"
---

这里我写了一中读取资源图片管理的方法，这个方法的好处就是，加载过的图片把它放在MAP里，下次再用的时候不用重新加载。



1.在这个plugin的最顶层目录下创建 icons文件，然后把图片放在这个文件夹里。


2.在这个plugin 里的Activator(默认是这个类名，一般自己会改成其他和PLUGIN相关的名字)里写static方法，这方法能根据图片所在地路径名字取得图片



```java
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。
例如。

```java
class ImgShows{
......
public Img getImg(String path){
Image img=Activator.getImage(path);

}
......

}
```


4.如果想把这个图放在CLabel里。最好这么写。这里我用formLayout.


```java
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);
```


这样的图大小工整。