Core Java Books

Friday 4 March 2011

Using Java2D to Create Icons at Runtime

I needed some marker Icons to display unique points on a map. Each icon needed to have a unique id so I wanted a number or letter to be placed on each icon. Obviously I did not want to create and store hundreds of icons in a directory, the simple solution would be to create them on the fly using Java2D.

I'm posting a basic solution which creates some fairly basic marker icons but it is a good starting point for people to start creating more fancy looking markers/icons/images.

Basically I make use of Java2D to draw into BufferedImage and then use the image to construct an ImageIcon.

The example code can be downloaded and creates the following demo images:


Now obviously this isn't created by anyone with artistic talent but it shows the basics.


Click on the following button to try it out.



(Java 1.6 required!)

I'd be interested to hear about any other solutions and any neat ways of extending this.

3 comments:

  1. Krill had blogged about this sometime back ..using SVG instead. http://weblogs.java.net/blog/kirillcool/archive/2006/08/svgbased_resiza_1.html

    ReplyDelete
  2. Yes an interesting piece. I had looked into SVG a while ago and it is something I may investigate further in future as it would be a good mechanism to re-use existing designs. Thanks for the link.

    ReplyDelete
  3. Steve,

    did you manage to generate icons on the fly with Android ? Once created how do you add them to the project at runtime ? I looking for a way of creating dynamic icon for notification bar ...

    Thanks !

    ReplyDelete