当我们需要自己绘制点9图时,比如游戏里面的某些ui元素,重写的view绘制需要canvas绘制点等情况时。
Android的.9图原理:(讲最特殊情况,即四个角不可拉伸,中间拉伸)。
1、使用边上一像素来标记一个图的可拉伸信息。
2、从中可读出四个信息,上边不可拉伸的高度,下边不可拉伸的高度,左边不可拉伸的宽度,右边不可拉伸的宽度
3、四个信息即可标识出一个九宫格,此处我就不画图了。
4、四个角为不可拉伸部分,上、下两边中间部分只能横向拉伸,左、右两边的中间部分只能竖直拉伸,中间板块为两个方向均可以拉伸。
Android读取.9图信息的代码(此代码不是本人自己所写,是本人的一个同伴查询Android源代码后写出来的,感谢一下这位小伙伴先)此代码大家可以直接拿出去用。
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Color;
public class NinePatchLoad {
private static final int TRANSPARENT = Color.TRANSPARENT;
private static final int BLACK = Color.BLACK;
/**
* Computes and returns the 9-patch chunks.
* @param image the image containing both the content and the control outer line.
* @return the {@link NinePatchChunk}.
*/
public static NinePatchChunk load(Bitmap image) {
ensure9Patch(image);
return createChunk(image);
}
/**
* Finds the 9-patch patches and padding from a {@link BufferedImage} image that contains
* both the image content and the control outer lines.
*/
private static NinePatchChunk createChunk(Bitmap image) {
// the size of the actual image content
int width = image.getWidth() - 2;
int height = image.getHeight() - 2;
int[] row = null;
int[] column = null;
// extract the patch line. Make sure to start at 1 and be only as long as the image content,
// to not include the outer control line.
row = getPixels(image, 1, 0, width, 1, row);
column = getPixels(image, 0, 1, 1, height, column);
boolean[] result = new boolean[1];
Pair<List<Pair<Integer>>> left = getPatches(column, result);
boolean mVerticalStartWithPatch = result[0];
result = new boolean[1];
Pair<List<Pair<Integer>>> top = getPatches(row, result);
boolean mHorizontalStartWithPatch = result[0];
int[] horizontalPatch;
if (mHorizontalStartWithPatch) {
horizontalPatch = getAlternativeLength(top.mSecond, top.mFirst);
} else {
horizontalPatch = getAlternativeLength(top.mFirst, top.mSecond);
}
int[] verticalPatch;
if (mVerticalStartWithPatch) {
verticalPatch = getAlternativeLength(left.mSecond, left.mFirst);
} else {
verticalPatch = getAlternativeLength(left.mFirst, left.mSecond);
}
int tLeft, tMiddle, tRight, lTop, lMiddle, lBottom;
if (horizontalPatch.length == 3) {
tLeft = horizontalPatch[0];
tM