Thursday, May 12, 2011

Color and Gradient for Eclipse


The Designerator Color Plugin consists of three components:
  • Color View
  • Color Dialog
  • Gradient Dialog

    Color View:

     


    This is the Eclipse Color Palette. You can copy Color values or drag Colors into the Editor. You can choose from different palettes or create your own. The Color view can also handle Photoshop 'aco' files.

    The Color Dialog:

     


    The main advantage of this Color Dialog is that you have direct feedback from the Color field. The code is simple and straight forward.

    
     HSBColorDialog colorDialog; 
     colorDialog = new HSBColorDialog(shell, true, colorListener);
     colorDialog.setColor(display, rgb);
     colorDialog.setAddButton(false);
     int code = colorDialog.open();
     if (code == Window.OK) {
      setColor(colorDialog.getRGB());
     }
     
    
    If you want direct feedback you pass an 'IColorListener' to the Dialog:
     
      final IColorListener updater = new IColorListener() {
       
       @Override
       public void update(RGB rgb) {
        setColor(rgb,shell);
       }
       
       @Override
       public void updateGradient(GradientData g, boolean addBut) {
       }
      };
     
    

    When ever the color changes, the IColorlistener will be notified. This is the complete example ShowColorDialog.java.

    The Gradient Dialog:

     

      
    The code to open the Dialog, passing a Gradient to the Dialog looks like this:

     
     GradientData data=null;
     RGB[] rgb = {new RGB(0, 0, 0), new RGB(255, 255, 255) };
     int[] percentage = { 0, 100 };
     int[] midpoints = { 50 };
     boolean vertical = false;
     boolean linear = true;
     boolean radial = false;
     data = new GradientData(rgb, midpoints, percentage,
     vertical, linear, 0, 0, radial);
      
     HSBColorDialog colorDialog = new HSBColorDialog(shell, false,updater);  
     colorDialog.setGradient(display, data);
     int code = colorDialog.open();
     if (code == Window.OK) {
      gradientData = colorDialog.getGradient();
     }
     
    

    You also can pass an IColorListener to the Dialog to get direct feedback. To paint the Gradient the Code again is quite simple:

     
     GC gc = e.gc;
     Rectangle clientArea = canvas.getClientArea();
     Image buffer = new Image(Display.getCurrent(), clientArea);
     GC bgc = new GC(buffer);
     if (gradientData != null) {
      LinearGradient.paintGradient(bgc, gradientData,
      clientArea.x, clientArea.y, clientArea.width,clientArea.height);
     }
     gc.drawImage(buffer, 0, 0);
     buffer.dispose();
     bgc.dispose();
     
    

    This is the complete example ShowGradientDialog.java. Both snippets are part of the org.designerator.color plugin for Eclipse.

    No comments:

    Post a Comment