public static final Image scale (Image srcImage, int newW, int newH) { int srcW = srcImage.getWidth(); int srcH = srcImage.getHeight(); //先做水平方向上的伸缩变换 Image tmp = Image.createImage(newW, srcH); Graphics g = tmp.getGraphics();
for (int x = 0; x < newW; x++) { g.setClip(x, 0, 1, srcH); //按比例放缩 g.drawImage(srcImage,x-x*srcWnewW,0,Graphics.LEFT Graphics.TOP);
}
//再做垂直方向上的伸缩变换 Image dst = Image.createImage(newW, newH); g = dst.getGraphics();
for (int y = 0; y < newH; y++) { g.setClip(0, y, newW, 1); //按比例放缩 g.drawImage(tmp,0,y-y*srcHnewH,Graphics.LEFT Graphics.TOP);
}
return dst; }
}
也许有同学会提出疑问,既然是按x,y方向按等比例放缩,那我写成这样岂不是代码更简洁:
public static final Image scale2(Image srcImage, int newW, int newH) { int srcW = srcImage.getWidth(); int srcH = srcImage.getHeight();
Image dst=Image.createImage(newW,newH); Graphics g=dst.getGraphics(); for (int x = 0; x < newW; x++) { for (int y = 0; y < newH; y++) { g.setClip(x, y, 1, 1); g.drawImage(srcImage, x-x*srcWnewW, y - y * srcH / newH, Graphics.LEFT Graphics.TOP);