在Android中调整Drawable的大小

时间:2011-08-11 06:16:07

标签: android image bitmap resize drawable

我正在为进度对话框设置一个drawable(pbarDialog),但我的问题是我想每次调整drawable的大小,但无法弄清楚如何。

以下是一些代码:

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();

7 个答案:

答案 0 :(得分:81)

以下对我有用:

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

答案 1 :(得分:20)

这是我结束的地方,部分归功于萨阿德的回答:

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;

}

答案 2 :(得分:8)

对于调整大小,这很好而且很短(上面的代码对我不起作用),找到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);

答案 3 :(得分:1)

也许我的解决方案不完全涵盖了这个问题,但我需要像“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"
    />

将此解决方案视为选项/想法。

答案 4 :(得分:1)

以上是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)

答案 5 :(得分:0)

如果源Drawable不是BitmapDrawable的instance(可能是使用矢量,彩色drawable等的情况),则投票最多的答案将不起作用。

最合适的解决方案是将Drawable绘制为具有设置位图的Canvas,如下所示:

<script>
    (async function () {

        const adapters = await window.WebChat.createDirectLineSpeechAdapters({
            fetchCredentials: {
                region: 'region',
                subscriptionKey: 'my subscription key'
            }
        }, ({ dispatch }) => next => action => {
            if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                dispatch({
                    type: 'WEB_CHAT/SEND_EVENT',
                    payload: {
                        name: 'webchat/join',
                        value: 'my username'
                    }
                });
            }

            return next(action);
        });

        window.WebChat.renderWebChat(
            {

                ...adapters
            },
            document.getElementById('webchat')
        );

        document.querySelector('#webchat > *').focus();
    })().catch(err => console.error(err));
</script>

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

const fs = require('fs');

let rawdata = fs.readFileSync('fileName.json');

let convertedData = String(rawdata)
    .replace(/\n/gi, ',')
    .slice(0, -1);

let JsonData= JSON.parse(`[${convertedData}]`); 

注意:总是在辅助线程中执行此操作!

答案 6 :(得分:0)

科特林方式

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

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())
    }