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



所以我想将一个从可绘制对象创建的位图设置为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保留在布局上,其可见性不可见。如果我像所示这样评论这 2 行,那么将没有可见的进度,例如可绘制对象是空的或透明的。看起来这个ImageView使可绘制真正绘制自己。但我不喜欢使用假ImageView只是为了让"魔术"发生,所以问题是 - 如何在没有这个假ImageView的情况下让它工作.
请不要建议我如何正确设置进度SeekBar例如:

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

或 xml 选择器方式或任何 altrnative 方式,因为我已经知道它并且我的静止并不是真的关于它。我只需要让它按照我的方式工作。
我只需要制作我的位图或画布或任何真正绘制的东西。
如果需要,可以提供更多详细信息(可选阅读(。问题在于可绘制seekbar_bg_full - 它是一个 9 个补丁的 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了!
然而,我的代码是一个很长的故事,可以摆脱可绘制的 9patch 功能。

最新更新