SeekBar:从 Drawable 获取空位图,直到将其设置为 ImageView 或如何从 9patch 获取生成的位图

SeekBar: getting empty bitmap from Drawable until set it to ImageView OR how to get resulting Bitmap from 9patch

所以我想将一个从drawable 创建的Bitmap 设置到SeekBar 的进度中。我是这样做的:

    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Drawable drawable = getResources().getDrawable(R.drawable.seekbar_bg_full);
    Canvas canvas = new Canvas(bmp);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas); // I assume here drawable must be drawn but its not
    // canvas.drawBitmap(bmp, 0 , 0, null); // does nothing as 4 me
    // encode/decode to detach bitmap from 9patch
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(CompressFormat.PNG, 0, baos);
    final byte[] bytes = baos.toByteArray();
    bmp.recycle();
    bmp = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
    // ClipDrawable is intented to be used as progressDrawable in SeekBar
    ClipDrawable progressDrawable = new ClipDrawable(new BitmapDrawable(getResources(),bmp), Gravity.LEFT, ClipDrawable.HORIZONTAL);
    // if not set this drawable to an ImageView then no progress will be shown by SeekBar at all
    //ImageView imgFake = (ImageView) findViewById(R.id.fakeImageView);
    //imgFake.setImageDrawable(progressDrawable);
    mySeekBar.setProgressDrawable(progressDrawable);

widthheight 是此处的有效值(如 460 和 30)。如您所见,有 2 行关于 ImageView 的代码被注释了。此 ImageView 保留在布局上并且其可见性是不可见的。如果我像显示的那样评论那两行,那么将不会有可见的进展,比如可绘制对象是空的或透明的。看起来这个 ImageView 使 drawable 真正绘制了自己。但我不喜欢使用假 ImageView 只是为了让 "magic" 发生所以问题是 - 如何在没有这个假 ImageView.
的情况下让它工作 请不要建议我如何正确设置 SeekBar 进度,例如:

ClipDrawable progressDrawable = new ClipDrawable(getResources().getDrawable(R.drawable.seekbar_bg_full), Gravity.LEFT, ClipDrawable.HORIZONTAL);
mySeekBar.setProgressDrawable(progressDrawable);

或 xml 选择器方式或任何替代方式,因为我已经知道它并且我的问题并不是真正关于它。我只需要让它按照我的方式工作。
我只需要制作我的位图或 canvas 或任何真正绘制的东西。
如果需要,可以提供更多详细信息(可选阅读)。问题是关于 drawable seekbar_bg_full - 它是一个 9-patch png。而所有需要的是获得一个非 NinePatchDrawable 链接的结果位图。假设我有一个 460x30px 的视图,其中 9patch 图像设置为 src 或背景,并且 9patch 图像被拉伸,就像它应该的那样。所以我需要获取此视图包含的位图,并且此位图不应以某种方式链接到 9patch。这就是为什么我将位图编码为一个字节数组,然后将其解码回来——这只是为了摆脱 9patch。如果有更简单的方法从 9patch 获取生成的位图(NinePatchDrawable 的一些魔法)- 我想知道它。

好的,我想出了如何摆脱伪造的 ImageView 并使可绘制对象自行绘制:我所要做的就是在可绘制对象上调用 setBounds() 方法:

ClipDrawable progressDrawable = new ClipDrawable(new BitmapDrawable(getResources(),bmp), Gravity.LEFT, ClipDrawable.HORIZONTAL);
progressDrawable.setBounds(0, 0, width, height);
mySeekBar.setProgressDrawable(progressDrawable);

终于不用ImageView了!
但是我的代码是一个很长的故事来摆脱 drawable 中的 9patch 功能。