鸿蒙之通过Java引用资源ID给Text控件四周添加图片不变形、不拉伸

问题出现的场景
  在安卓里面,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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值