gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:42:39 26 4
gpt4 key购买 nike

我正在尝试从这里实现分段单选按钮: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);
}

请大家指教。我真的需要帮助。谢谢。

最佳答案

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

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

稍后在您的主代码中调用它:

button.setImage(drawable);

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

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

(我是 SegmentedRadioButton 的维护者)

关于android - 将可绘制图像传递给 Android 中的 TypedArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com