在Android中调整Drawable大小

pxyaymoc  于 2024-01-04  发布在  Android
关注(0)|答案(8)|浏览(176)

我正在为进度对话框(pbarDialog)设置一个可绘制对象,但我的问题是我每次都想调整可绘制对象的大小,但不知道如何调整。
下面是一些代码:

Handler progressHandler = new Handler() {

    public void handleMessage(Message msg) {
        switch (msg.what) {
            // some more code
            case UPDATE_PBAR:
                pbarDialog.setIcon(mAppIcon);
                pbarDialog.setMessage(mPbarMsg);
                pbarDialog.incrementProgressBy(mIncrement+1);
                break;
        }
    }
};

pbarDialog.show();

Thread myThread = new Thread(new Runnable() {

    public void run() {
        // some code
        for (int i = 0; i < mApps.size(); i++) {
            mAppIcon = mAdapter.getIcons().get(mApps.get(i).getPackageName());
            // need to resize drawable here
            progressHandler.sendEmptyMessage(UPDATE_PBAR);
        }
        handler.sendEmptyMessage(DISMISS_PBAR);
    }

});

myThread.start();

字符串

vybvopom

vybvopom1#

以下为我工作:

private Drawable resize(Drawable image) {
    Bitmap b = ((BitmapDrawable)image).getBitmap();
    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 50, 50, false);
    return new BitmapDrawable(getResources(), bitmapResized);
}

字符串

2sbarzqh

2sbarzqh2#

这是我最终的结果,部分归功于萨阿德的回答:

public Drawable scaleImage (Drawable image, float scaleFactor) {

    if ((image == null) || !(image instanceof BitmapDrawable)) {
        return image;
    }

    Bitmap b = ((BitmapDrawable)image).getBitmap();

    int sizeX = Math.round(image.getIntrinsicWidth() * scaleFactor);
    int sizeY = Math.round(image.getIntrinsicHeight() * scaleFactor);

    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, sizeX, sizeY, false);

    image = new BitmapDrawable(getResources(), bitmapResized);

    return image;

}

字符串

8cdiaqws

8cdiaqws3#

对于我来说,这是一个很好的短代码(上面的代码对我来说不起作用),找到了here

ImageView iv = (ImageView) findViewById(R.id.imageView);
  Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
  Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, newWidth, newHeight, true);
  iv.setImageBitmap(bMapScaled);

字符串

a11xaf1n

a11xaf1n4#

以下是上述答案的组合,作为Kotlin扩展

fun Context.scaledDrawableResources(@DrawableRes id: Int, @DimenRes width: Int, @DimenRes height: Int): Drawable {
    val w = resources.getDimension(width).toInt()
    val h = resources.getDimension(height).toInt()
    return scaledDrawable(id, w, h)
}

fun Context.scaledDrawable(@DrawableRes id: Int, width: Int, height: Int): Drawable {
    val bmp = BitmapFactory.decodeResource(resources, id)
    val bmpScaled = Bitmap.createScaledBitmap(bmp, width, height, false)
    return BitmapDrawable(resources, bmpScaled)
}

字符串
使用方法:

val scaled = context.scaledDrawableResources(R.drawable.ic_whatever, R.dimen.width, R.dimen.height)
imageView.setImageDrawable(scaled)


val scaled = context.scaledDrawable(R.drawable.ic_whatever, 100, 50)
imageView.setImageDrawable(scaled)

afdcj2ne

afdcj2ne5#

也许我的解决方案没有完全解决这个问题,但是我需要一个类似于“CustomDrawable”的东西。
换句话说,我想在一个圆形前面设置一个标志。所以我创建了一个带有背景的FrameLayout(只是一个彩色的圆形),在这个圆形前面显示标志。

要调整徽标的大小,我通过缩放缩小徽标-这里是一些代码:

iv = new ImageView(mContext);

iv.setScaleX(0.75f); // <- resized by scaling 
iv.setScaleY(0.75f);

// loading the drawable from a getter (replace this with any drawable)
Drawable drawable = ML.loadIcon(mContext, Integer.parseInt(icon));

iv.setImageDrawable(drawable);

// icon get's shown inside a ListView
viewHolder.mIvIcon.addView(iv);

字符串
下面是FrameLayout,它显示ListView行中的图标:

<FrameLayout
    android:id="@+id/iv_card_icon"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/circle"
    android:layout_marginStart="16dp"
    />


将此解决方案视为一种选择/想法。

nszi6y05

nszi6y056#

如果源Drawable不是BitmapDrawable的instanceofBitmapDrawable,那么投票最多的答案将不起作用,这可能是使用矢量,颜色drawable等的情况。
最合适的解决方案可能是将Drawable绘制到具有设置位图的Canvas中,如下所示:

@NonNull final Drawable drawable = yourSourceDrawable;

// Define the Canvas and Bitmap the drawable will be drawn against
final Canvas c = new Canvas();
c.setBitmap(bitmap);

// Draw the scaled drawable into the final bitmap
if (yourSourceDrawable!= null) {
    yourSourceDrawable.setBounds(0, 0, newWidth, newHeight);
    yourSourceDrawable.draw(c);
}

字符串
奖金:计算要应用的比例(例如,当缩放Drawable到视图时):

if (drawable != null && drawable.getIntrinsicWidth() > 0 && drawable.getIntrinsicHeight() > 0) {
    // the intrinsic dimensions can be -1 in some cases such as ColorDrawables which aim to fill 
    // the whole View
    previewWidth = drawable.getIntrinsicWidth();
    previewHeight = drawable.getIntrinsicHeight();
}

final float widthScale = mViewWidth / (float) (previewWidth);
if (widthScale != 1f)
    newWidth = Math.max((int)(widthScale * previewWidth), 1);

final float heightScale = mViewHeight / (float) (previewHeight);
if (heightScale != 1f)
    newHeight = Math.max((int)(heightScale * previewHeight), 1);

注意:始终在工作线程中执行此操作!

uinbv5nw

uinbv5nw7#

Kotlin方式

最后对我有用的是这个简单的解决方案

fun resizeDrawable(width:Int, height:Int): Drawable {
        val drawable = ResourceUtils.getDrawable(R.drawable.ic_info)
        val bitmap = drawable.toBitmap(width, height) //here width and height are in px
        return bitmap.toDrawable(getResources())
    }

字符串

hgncfbus

hgncfbus8#

对于任何仍然在这个问题上挣扎的人,请记住,这里最受欢迎的答案并不是正确的方法。如果你拥有的Drawable不是从BitmapDrawable扩展的,那么将任何Drawable转换为BitmapDrawable是行不通的,你会得到一个ClassCastException。
这是我最终使用的代码,它适用于每一种Drawable:
Kotlin酒店

fun Context.getResizedDrawable(
    @DrawableRes drawableId: Int,
    @DimenRes size: Int,
): Drawable? {
    val dimen = resources.getDimensionPixelSize(size)

    return ContextCompat.getDrawable(this, drawableId)?.let { drawable ->
        val bitmap = Bitmap.createBitmap(dimen, dimen, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)

        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)

        BitmapDrawable(this.resources, bitmap)
    }
}

字符串

** java **

@Nullable
public Drawable getResizedDrawable(
    Context context,
    @DrawableRes int drawableId,
    @DimenRes int size
) {
    int dimen = context.getResources().getDimensionPixelSize(size);
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    Bitmap bitmap = Bitmap.createBitmap(dimen, dimen, Bitmap.Config.ARGB_8888);

    if (drawable != null) {
        Canvas canvas = new Canvas(bitmap);
        
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return new BitmapDrawable(context.getResources(), bitmap);
    } else {
        return null;
    }
}

相关问题