问题出现的场景
在安卓里面,TextView是可以通过以下代码给四周设置图片的
Drawable drawable = context.getDrawable(R.drawable.xxx);
text.setCompoundDrawables(drawable, drawable, drawable, drawable);
. 当然drawable对象还需要调用下面这行代码才能看得到
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
. 鸿蒙的Text控件也有类似的方法:
Resource resource = context.getResourceManager().getResource(ResourceTable.Media_xxx);
PixelMapElement element = new PixelMapElement(resource)
text.setAroundElements(element, element, element, element)
出现的问题
但是因为上面这种写法需要element设置bounds,否则将会拉伸图片,而element的getWidth()、getMinWidth()、getHeigth()、getMinHeigth()这四个方法拿到的数据要么是0,要么是-1,这就是我遇到的问题。
解决思路
细心一点会发现PixelMapElement对象还有一个getPixelMap()方法,里面也有前面那四个方法,但是调用的时候会抛出空指针,目前因为看不到源码,但是可以猜想PixelMapElement对象的四个方法与getPixelMap()的返回值或许是有关联的。
PixelMapElement的构造方法有三个,其中有一个就是传递PixelMap对象,那是不是只要我们想办法获取到PixelMap对象,再通过构造方法设置PixelMap对象,那么是不是就可以解决问题了呢?
问题和思路都有了,那么也不废话了,直接放出代码。
/**获取字节数组
* @param resource 继承自InputStream类
* @return 字节数组
*/
private static byte[] convertToByteArray(Resource resource) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] readByte = new byte[1024];
int line;
while((line = resource.read(readByte, 0, readByte.length)) > 0) {
outputStream.write(readByte, 0, line);
}
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**通过资源ID获取图片对象
* @param context 上下文
* @param resId 资源ID
* @return 图片对象
*/
public static PixelMapElement getImage(Context context, int resId){
try {
Resource resource = context.getResourceManager().getResource(resId);
ImageSource imageSource = ImageSource.create(convertToByteArray(resource), null);
PixelMap pixelMap = imageSource.createPixelmap(new ImageSource.DecodingOptions());
//经测试,此处不再setBounds()方法,图片也能正常显示了
return new PixelMapElement(pixelMap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}