<<J2SE>>Java代码自写9Path算法

来源:互联网 发布:清华同方教学软件 编辑:程序博客网 时间:2024/06/05 16:13

<<J2SE>>Java代码自写9Path算法:

简而言之:在Android的OS上对于背景图片的缩放有很好的9Path机制(对自己指定的区域进行缩放)可以达到对图片的缩放不会失真的效果。然而对于J2SE桌面程序就没有这么好的东东,于是自己就写了个简易的9Path算法。看网上很少就决定发布出来。下面是代码:

/** *  */package com.edu.nsu.md.view.component;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;/** * 自定义Image类 *  * @author Berwin *  */public class MImage {private BufferedImage bImage;/** * 自定义图片组件的构造函数 *  * @param filePath *            文件路径 */public MImage(String filePath) {try {this.bImage = ImageIO.read(new File(filePath));} catch (IOException e) {e.printStackTrace();}}/** * 通过9Path对图片放大到指定的宽高 *  * @param dWidth *            要放大到的宽度 * @param dHeight *            要放大到的高度 * @return 返回BufferedImage对象 */public BufferedImage toNinePathImage(int dWidth, int dHeight) {BufferedImage newBImage = null;List<Integer> xPix = new ArrayList<Integer>();List<Integer> yPix = new ArrayList<Integer>();// 得到边框的rgb值,并判断是否为黑色,是就保存,不是就不保存for (int w = 0; w < bImage.getWidth(); w++) {for (int h = 0; h < bImage.getHeight(); h++) {if (h == 0 || w == 0) {int rgb = bImage.getRGB(w, h);int r = (rgb & 0xff0000) >> 16;int g = (rgb & 0xff00) >> 8;int b = (rgb & 0xff);if (r == 0 && g == 0 && b == 0) {if (w == 0) {yPix.add(h);} else if (h == 0) {xPix.add(w);}}}}}// 计算x轴所有黑色像素点的拉伸像素点值int allXZonePixs = dWidth - (bImage.getWidth() - 2 - xPix.size());// 计算x轴每个黑色像素点的拉伸像素点值int oneXZonePix = (xPix.size() != 0 ? (allXZonePixs / xPix.size()): (dWidth / (bImage.getWidth() - 2)));// ************************************// 计算y轴所有黑色像素点的拉伸像素点值int allYZonePixs = dHeight - (bImage.getHeight() - 2 - yPix.size());// 计算y轴每个黑色像素点的拉伸像素点值int oneYZonePix = (yPix.size() != 0 ? (allYZonePixs / yPix.size()): (dHeight / (bImage.getHeight() - 2)));// ************************************// 创建一个新的BufferedImage对象newBImage = new BufferedImage(dWidth, dHeight,BufferedImage.TYPE_INT_ARGB);// 通过BufferedImage得到Graphics对象Graphics g = newBImage.getGraphics();int startX = 0;for (int w = 1; w < bImage.getWidth() - 1; w++) {boolean xIsBlack = (xPix.contains(w) || xPix.size() == 0);int startY = 0;for (int h = 1; h < bImage.getHeight() - 1; h++) {boolean yIsBlack = (yPix.contains(h) || yPix.size() == 0);g.drawImage(bImage, startX, startY, startX+ (xIsBlack ? oneXZonePix : 1), startY+ (yIsBlack ? oneYZonePix : 1), w, h, w + 1, h + 1,null);startY += (yIsBlack ? oneYZonePix : 1);}startX += (xIsBlack ? oneXZonePix : 1);}return newBImage;}}

**在运行前一定要将图片左、上的黑色点处理好。

如果想看到效果可以将得到的图片通过下面的方法保存到指定路径:

ImageIO.write(toNinePathImage(100, 100), "png", new File("./pictures/test/tset_9path.png"));


0 0
原创粉丝点击