Di Java ME terkadang penggunaan image menjadi masalah, ukuran screen dari display yang berbeda-beda. Ada kalanya kita perlu untuk melakukan manipulasi pada gambar, di sini gw bakal kasih satu method simple untuk melakukan resize image.
- public static Image resizeImage(Image src, int newWidth, int newHeight) {
- int srcWidth = src.getWidth();
- int srcHeight = src.getHeight();
- Image tmp = Image.createImage(newWidth, srcHeight);
- Graphics g = tmp.getGraphics();
- int ratio = (srcWidth << 16) / newWidth;
- int pos = ratio/2;
- //Horizontal Resize
- for (int x = 0; x < newWidth; x++) {
- g.setClip(x, 0, 1, srcHeight);
- g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP);
- pos += ratio;
- }
- Image resizedImage = Image.createImage(newWidth, newHeight);
- g = resizedImage.getGraphics();
- ratio = (srcHeight << 16) / newHeight;
- pos = ratio/2;
- //Vertical resize
- for (int y = 0; y < newHeight; y++) {
- g.setClip(0, y, newWidth, 1);
- g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP);
- pos += ratio;
- }
- return resizedImage;
- }
Post a Comment