将可绘制图像传递给Android中的TypedArray

时间:2011-12-12 11:30:35

标签: android android-layout android-canvas

我正在尝试从这里实现一个分段单选按钮:https://github.com/makeramen/android-segmentedradiobutton但我需要以编程方式而不是XML格式设置图像。

这是自定义RadioButton的来源:

public class CenteredImageButton extends RadioButton {

    Drawable image;

    public CenteredImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.CompoundButton, 0, 0);
        image = a.getDrawable(1);
        setButtonDrawable(android.R.id.empty);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (image != null) {
            image.setState(getDrawableState());

            // scale image to fit inside button

            int imgHeight = image.getIntrinsicHeight();
            Log.d("IMAGEHEIGHT", "imageWidth is " + imgHeight);

            int imgWidth = image.getIntrinsicWidth();
            Log.d("IMAGEWIDTH", "imageWidth is " + imgWidth);

            int btnWidth = getWidth();
            Log.d("BUTTONWIDTH", "buttonWidth is " + btnWidth);
            int btnHeight = getHeight();
            Log.d("BUTTONHEIGHT", "buttonHeight is " + btnHeight);

            float scale;

            if (imgWidth <= btnWidth && imgHeight <= btnHeight) {
                scale = 1.0f;
            } else {
                scale = Math.min((float) btnWidth / (float) imgWidth,
                        (float) btnHeight / (float) imgHeight);
            }

            Log.d("SCALE", "scale is " + scale);

            int dx = (int) ((btnWidth - imgWidth * scale) * 0.5f + 0.5f);
            Log.d("DX", "dx is " + dx);
            int dy = (int) ((btnHeight - imgHeight * scale) * 0.5f + 0.5f);
            Log.d("DY", "dy is " + dy);

            image.setBounds(dx, dy, (int) (dx + imgWidth * scale),
                    (int) (dy + imgHeight * scale));

            image.draw(canvas);
        }
    }

我在另一个文件中设置drawable:

private void setButtonImageProperties(RadioButton button,Drawable drawable){
    button.setGravity(Gravity.CENTER);
    Resources resources = this.context.getResources();
    float dipValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            60, resources.getDisplayMetrics());
    float dipValue1 = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 80, resources.getDisplayMetrics());

    button.setMinHeight((int) dipValue);
    button.setMinWidth((int) dipValue1);

    button.setButtonDrawable(drawable);
}

请任何人,建议。我真的需要帮助。感谢。

1 个答案:

答案 0 :(得分:2)

您几乎需要将一个setImage方法添加到CenteredImageButton:

public void setImage(Drawable newImage) {
    image = newImage;
}

稍后在主代码中调用它:

button.setImage(drawable);

请参阅此要点以查看内联方法:https://gist.github.com/1470789

我还注意到你将我的班级名称从CenteredRadioImageButton改为CenteredImageButton。如果您实际上没有将此用于类似RadioButton的行为,我建议使用标准ImageButton

(我是SegmentedRadioButton

的维护者