Created
December 20, 2012 19:01
-
-
Save azhawkes/4347761 to your computer and use it in GitHub Desktop.
Simple Java/SWT class for image sprites. Quickly slice up a larger image into smaller ones, while preserving alpha transparency. Most of the existing examples out there don't handle alphas properly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.andyhawkes.gists; | |
import org.eclipse.swt.graphics.Image; | |
import org.eclipse.swt.graphics.ImageData; | |
import org.eclipse.swt.graphics.Rectangle; | |
import org.eclipse.swt.widgets.Display; | |
/** | |
* Simple class that demonstrates how to slice up regions of a sprite image in SWT, while preserving | |
* alpha transparency. There are shorter ways to do this if you don't care about alpha transparency. | |
*/ | |
public class SwtImageSprite { | |
private Image sprite; | |
public SwtImageSprite(Image sprite) { | |
this.sprite = sprite; | |
} | |
public Image loadImageFromRegion(Rectangle region) { | |
ImageData data = new ImageData(region.width, region.height, sprite.getImageData().depth, sprite.getImageData().palette); | |
int[] pixels = new int[region.width]; | |
byte[] alphas = new byte[region.width]; | |
for (int y = 0; y < region.height; y++) { | |
sprite.getImageData().getAlphas(region.x, region.y + y, region.width, alphas, 0); | |
sprite.getImageData().getPixels(region.x, region.y + y, region.width, pixels, 0); | |
data.setPixels(0, y, region.width, pixels, 0); | |
data.setAlphas(0, y, region.width, alphas, 0); | |
} | |
return new Image(Display.getCurrent(), data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment