以编程方式设置可绘制大小

时间:2011-01-05 21:35:07

标签: java android

图像(图标)的大小大致相同,但我需要调整它们的大小,以使按钮保持相同的高度。

我该怎么做?

Button button = new Button(this);
button.setText(apiEventObject.getTitle());
button.setOnClickListener(listener);

/*
 * set clickable id of button to actual event id
 */
int id = Integer.parseInt(apiEventObject.getId());
button.setId(id);

button.setLayoutParams(new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

Drawable drawable = LoadImageFromWebOperations(apiSizeObject.getSmall());
//?resize drawable here? drawable.setBounds(50, 50, 50, 50);
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);

14 个答案:

答案 0 :(得分:138)

setBounds()方法不适用于每种类型的容器(但对我的某些ImageView确实有效)。

尝试使用以下方法缩放drawable本身:

// Read your drawable from somewhere
Drawable dr = getResources().getDrawable(R.drawable.somedrawable);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
// Scale it to 50 x 50
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));
// Set your new, scaled drawable "d"

答案 1 :(得分:31)

使用setBounds()指定尺寸,即使用尺寸为50x50

drawable.setBounds(0, 0, 50, 50);
  

public void setBounds(int left,int top,int right,int bottom)

答案 2 :(得分:14)

在应用之前.setBounds(..)尝试将当前的Drawable转换为ScaleDrawable

drawable = new ScaleDrawable(drawable, 0, width, height).getDrawable();

之后

drawable.setBounds(0, 0, width, height);

将起作用

答案 3 :(得分:8)

我没有时间去挖掘为什么setBounds()方法没有像预期的那样处理bitmap drawable,但是我很少调整@androbean-studio解决方案来做setBounds应该做的事情......

/**
 * Created by ceph3us on 23.05.17.
 * file belong to pl.ceph3us.base.android.drawables
 * this class wraps drawable and forwards draw canvas
 * on it wrapped instance by using its defined bounds
 */
public class WrappedDrawable extends Drawable {

    private final Drawable _drawable;
    protected Drawable getDrawable() {
        return _drawable;
    }

    public WrappedDrawable(Drawable drawable) {
        super();
        _drawable = drawable;
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        //update bounds to get correctly
        super.setBounds(left, top, right, bottom);
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setBounds(left, top, right, bottom);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setAlpha(alpha);
        }
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.setColorFilter(colorFilter);
        }
    }

    @Override
    public int getOpacity() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getOpacity()
                : PixelFormat.UNKNOWN;
    }

    @Override
    public void draw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            drawable.draw(canvas);
        }
    }

    @Override
    public int getIntrinsicWidth() {
        Drawable drawable = getDrawable();
        return drawable != null
                ? drawable.getBounds().width()
                : 0;
    }

    @Override
    public int getIntrinsicHeight() {
        Drawable drawable = getDrawable();
        return drawable != null ?
                drawable.getBounds().height()
                : 0;
    }
}

用法:

// get huge drawable 
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper           
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper 
wrappedDrawable.setBounds(0,0,32,32); 
// use wrapped drawable 
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);

结果

之前的

enter image description here之后:enter image description here

答案 4 :(得分:6)

使用

textView.setCompoundDrawablesWithIntrinsicBounds()

你的minSdkVersion应该是build.gradle中的17

    defaultConfig {
    applicationId "com.example..."
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
}

更改可绘制尺寸:

    TextView v = (TextView)findViewById(email);
    Drawable dr = getResources().getDrawable(R.drawable.signup_mail);
    Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
    Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 80, 80, true));

    //setCompoundDrawablesWithIntrinsicBounds (image to left, top, right, bottom)
    v.setCompoundDrawablesWithIntrinsicBounds(d,null,null,null);

答案 5 :(得分:3)

使用post方法达到预期效果:

{your view}.post(new Runnable()
    {
        @Override
        public void run()
        {
            Drawable image = context.getResources().getDrawable({drawable image resource id});
            image.setBounds(0, 0, {width amount in pixels}, {height amount in pixels});
            {your view}.setCompoundDrawables(image, null, null, null);
        }
    });

答案 6 :(得分:3)

可能有点晚了。但是这里的解决方案在各种情况下最终都适用于我。

我们的想法是创建一个具有固定内部大小的自定义drawable,并将绘图作业传递给原始drawable。

Drawable icon = new ColorDrawable(){
        Drawable iconOrig = resolveInfo.loadIcon(packageManager);

        @Override
        public void setBounds(int left, int top, int right, int bottom){
            super.setBounds(left, top, right, bottom);//This is needed so that getBounds on this class would work correctly.
            iconOrig.setBounds(left, top, right, bottom);
        }

        @Override
        public void draw(Canvas canvas){
            iconOrig.draw(canvas);
        }

        @Override
        public int getIntrinsicWidth(){
            return  mPlatform.dp2px(30);
        }

        @Override
        public int getIntrinsicHeight(){
            return  mPlatform.dp2px(30);
        }
    };

答案 7 :(得分:1)

您可以创建视图类型的子类,并覆盖onSizeChanged方法。

我想在我的文本视图中使用缩放复合drawable,这不需要我在xml等中定义位图drawable,并且这样做:

public class StatIcon extends TextView {

    private Bitmap mIcon;

    public void setIcon(int drawableId) {
    mIcon = BitmapFactory.decodeResource(RIApplication.appResources,
            drawableId);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if ((w > 0) && (mIcon != null))
            this.setCompoundDrawablesWithIntrinsicBounds(
                null,
                new BitmapDrawable(Bitmap.createScaledBitmap(mIcon, w, w,
                        true)), null, null);

        super.onSizeChanged(w, h, oldw, oldh);
    }

}

(请注意,我使用了w两次,而不是h,因为在这种情况下我将图标放在文本上方,因此图标的高度不应与文本视图相同)

这可以应用于背景绘图,或者您想要相对于视图大小调整大小的任何其他内容。第一次创建View时调用onSizeChanged(),因此初始化大小时不需要任何特殊情况。

答案 8 :(得分:0)

您只能在一个图层和setLayerInset方法中使用LayerDrawable:

Drawable[] layers = new Drawable[1];
layers[0] = application.getResources().getDrawable(R.drawable.you_drawable);

LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setLayerInset(0, 10, 10, 10, 10);

答案 9 :(得分:0)

问了问题已经有一段时间了
但是对于许多人来说,如何做这件简单的事情仍不清楚。

在这种情况下,当将Drawable用作TextView(按钮)上的可绘制复合图像时,这非常简单。

所以您必须做两件事:

1。设置范围:

drawable.setBounds(left, top, right, bottom)

2。适当地设置可绘制对象(不使用内部边界):

button.setCompoundDrawablesRelative(drawable, null, null, null)
  • 无需使用位图
  • 没有诸如ScaleDrawable ColorDrawableLayerDrawable之类的变通办法(肯定是为其他目的而创建的)
  • 无需自定义可绘制对象!
  • post的解决方法
  • 这是一个本机且简单的解决方案,正是Android希望您做到的。

答案 10 :(得分:0)

jkhouw1答案是正确的,但是缺少一些细节,请参见下文:

至少对于API> 21来说要容易得多。 假设我们从资源中获取了VectorDrawable(用于检索它的示例代码):

val iconResource = context.resources.getIdentifier(name, "drawable", context.packageName)
val drawable = context.resources.getDrawable(iconResource, null)

为此VectorDrawable只需设置所需的大小:

drawable.setBounds(0, 0, size, size)

并在按钮中显示可绘制对象:

button.setCompoundDrawables(null, drawable, null, null)

就是这样。但是请注意使用setCompoundDrawables(非内部版本)!

答案 11 :(得分:0)

您可以尝试button.requestLayout()。更改背景大小时,需要重新测量和布局,但不会这样做

答案 12 :(得分:0)

使用LayerDrawable完成这项工作:

fun getResizedDrawable(drawable: Drawable, scale: Float) =
    LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, (drawable.intrinsicWidth * scale).toInt(), (drawable.intrinsicHeight * scale).toInt()) }

fun getResizedDrawable(drawable: Drawable, scalex: Float, scaleY: Float) =
    LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, (drawable.intrinsicWidth * scalex).toInt(), (drawable.intrinsicHeight * scaleY).toInt()) }

fun getResizedDrawableUsingSpecificSize(drawable: Drawable, newWidth: Int, newHeight: Int) =
    LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, newWidth, newHeight) }

示例:

val drawable = AppCompatResources.getDrawable(this, android.R.drawable.sym_def_app_icon)!!
val resizedDrawable = getResizedDrawable(drawable, 3f)
textView.setCompoundDrawablesWithIntrinsicBounds(resizedDrawable, null, null, null)
imageView.setImageDrawable(resizedDrawable)

答案 13 :(得分:-38)

Button button = new Button(this);
Button = (Button) findViewById(R.id.button01);

使用Button.setHeight()Button.setWeight()并设置值。