首先,您必须使用ImageSource.DecodingOptions解码图像资源,然后从PixelMap创建PixelMapElement。最后使用setIconElement API将PixelMapElement设置为 Tab ,
public static void createIcons(AbilitySlice abilitySlice, TabList.Tab tab, int id) {
if (tab == null) {
LogUtil.error(TAG, "createTabIcon failed");
return;
}
try {
PixelMap pixelMap = createByResourceId(abilitySlice, id, "image/png");
PixelMapElement pixelMapElement = new PixelMapElement(pixelMap);
pixelMapElement.setBounds(0, 0, 70, 70);
tab.setIconElement(pixelMapElement);
tab.setPadding(5, 5, 5, 5);
} catch (NotExistException | IOException e) {
LogUtil.error(TAG, "createTabIcon " + e.getLocalizedMessage());
}
}
public static PixelMap createByResourceId(AbilitySlice abilitySlice, int id, String str)
throws IOException, NotExistException {
if (abilitySlice == null) {
LogUtil.error(TAG, "createByResourceId but slice is null");
throw new IOException();
} else {
ResourceManager resourceManager = abilitySlice.getResourceManager();
if (resourceManager != null) {
Resource resource = resourceManager.getResource(id);
if (resource != null) {
ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
sourceOptions.formatHint = str;
ImageSource create = ImageSource.create(readResource(resource), sourceOptions);
resource.close();
if (create != null) {
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
decodingOptions.desiredSize = new Size(0, 0);
decodingOptions.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
PixelMap pixelMap = create.createPixelmap(decodingOptions);
return pixelMap;
}
LogUtil.error(TAG, "imageSource is null");
throw new FileNotFoundException();
}
LogUtil.error(TAG, "get resource failed");
throw new IOException();
}
LogUtil.error(TAG, "get resource manager failed");
throw new IOException();
}
}
private static byte[] readResource(Resource resource) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bArr = new byte[1024];
while (true) {
try {
int read = resource.read(bArr, 0, 1024);
if (read == -1) {
break;
}
byteArrayOutputStream.write(bArr, 0, read);
} catch (IOException e) {
LogUtil.error(TAG, "readResource failed " + e.getLocalizedMessage());
}finally {
byteArrayOutputStream.close();
}
}
LogUtil.debug(TAG, "readResource finish");
LogUtil.debug(TAG, "readResource len: " + byteArrayOutputStream.size());
return byteArrayOutputStream.toByteArray();
}