Skip to content

Instantly share code, notes, and snippets.

@albertofwb
Created July 10, 2018 02:13
Show Gist options
  • Save albertofwb/0e1cdc9cdce012822705a344a9d92b96 to your computer and use it in GitHub Desktop.
Save albertofwb/0e1cdc9cdce012822705a344a9d92b96 to your computer and use it in GitHub Desktop.
swt custom widget support gif animation
// copy from: https://stackoverflow.com/questions/13479833/java-swt-animated-gif
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
public class AnimatedGif extends Canvas {
private final ImageLoader loader = new ImageLoader();
private int img = 0;
private volatile boolean animating = false;
private Thread animateThread;
public AnimatedGif(Composite parent, int style) {
super(parent, style);
}
public void load (InputStream resource) {
loader.load(resource);
}
public void load (String path) throws IOException {
loader.load(new FileInputStream(new File(path)));
}
public void animate() {
if (animateThread == null) {
animateThread = createThread();
animateThread.setDaemon(true);
}
if (animateThread.isAlive())
return;
animateThread.start();
}
public void stop() {
animating = false;
if (animateThread != null)
try {
animateThread.join();
animateThread = null;
} catch (InterruptedException e) {
// do nothing
}
}
private Thread createThread() {
return new Thread() {
long currentTime = System.currentTimeMillis();
final Display display = getParent().getDisplay();
public void run() {
animating = true;
while(animating) {
img = (img == loader.data.length-1) ? 0 : img + 1;
int delayTime = Math.max(50, 10*loader.data[img].delayTime);
long now = System.currentTimeMillis();
long ms = Math.max(currentTime + delayTime - now, 5);
currentTime += delayTime;
try {
Thread.sleep(ms);
} catch(Exception e) {
return;
}
if (!display.isDisposed())
display.asyncExec(new Runnable() {
@Override
public void run() {
if (!AnimatedGif.this.isDisposed()) {
ImageData nextFrameData = loader.data[img];
Image frameImage = new Image(display, nextFrameData);
new GC(AnimatedGif.this).drawImage(frameImage, nextFrameData.x, nextFrameData.y);
frameImage.dispose();
}
}
});
}
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (!AnimatedGif.this.isDisposed()) {
new GC(AnimatedGif.this).fillRectangle(
0,
0,
getBounds().width,
getBounds().height);
}
}
});
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment