NinePatchDrawable创建实例

Home / Android MrLee 2016-10-21 2986

有些时候在做SDK需要内置一些图片,做安卓开发的都知道一般图片是放在drawable-***目录下面的。而一般SDK只有一个*.jar文件,那么图片怎么整呢。普通的图片还好,放在jar包文件的assets目录下,因为最终引用工程会把这个整合到一起。但是如果是.9的图片呢?我们也是有办法的,代码来实现!
	public static Bitmap getDrawable(Resources res, TypedValue value,
			InputStream stream, Rect rect, BitmapFactory.Options options) {
		if (options == null)
			options = new BitmapFactory.Options();
		if ((options.inDensity == 0) && (value != null)) {
			int i = value.density;
			if (i == 0)
				options.inDensity = 160;
			else if (i != 65535)
				options.inDensity = i;
		}
		if ((options.inTargetDensity == 0) && (res != null))
			options.inTargetDensity = res.getDisplayMetrics().densityDpi;
		return BitmapFactory.decodeStream(stream, rect, options);
	}
	private static Drawable getDrawable(Resources res, Bitmap bitmap,
			byte[] paramArrayOfByte, Rect rect, String path) {
		if (paramArrayOfByte != null)
			return new NinePatchDrawable(res, bitmap, paramArrayOfByte, rect,
					path);
		return new BitmapDrawable(res, bitmap);
	}
	public static Drawable getDrawable(Resources res, TypedValue value,
			InputStream stream, String path, BitmapFactory.Options options) {
		if (stream == null)
			return null;
		Rect rect = new Rect();
		if (options == null)
			options = new BitmapFactory.Options();
		Bitmap bitmap = getDrawable(res, value, stream, rect, options);
		if (bitmap != null) {
			byte[] arrayOfByte = bitmap.getNinePatchChunk();
			if ((arrayOfByte == null)
					|| (!NinePatch.isNinePatchChunk(arrayOfByte))) {
				arrayOfByte = null;
				rect = null;
			}
			return getDrawable(res, bitmap, arrayOfByte, rect, path);
		}
		return null;
	}
	public Drawable getDrawable(Resources res, String path) {
		try {
			InputStream stream = getAssets().open(path);
			TypedValue value = new TypedValue();
			value.density = 240;
			if (Build.VERSION.SDK_INT > 3) {
				return getDrawable(res, value, stream, path, null);
			}
			return Drawable.createFromResourceStream(res, value, stream, path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

voice_bg-9

 这张.9的图片,可以无限放大。

20161021143625

本文链接:https://www.it72.com/10945.htm

推荐阅读
最新回复 (0)
返回