gpt4 book ai didi

java - Android - 自定义 ImageView,带有勾选标记图像为选定状态

转载 作者:太空宇宙 更新时间:2023-11-04 13:49:42 25 4
gpt4 key购买 nike

对于我正在构建的 Android 应用程序,我制作了一个自定义 ImageView 类,它需要在图像上显示一个勾号,表明该图像已被选择。我从可绘制资源加载了刻度图像并将其显示在图像顶部,效果很好。但我想做的是,当刻度线可见时(即选择图像时),图像变暗,以便您可以清楚地看到刻度线。我怎样才能做到这一点?

目前我的代码如下:

public class TickedImageView extends ImageView {

private boolean selected = true;
private Bitmap tickBmp;
private Paint paint = new Paint();

public TickedImageView(Context context) {
super(context);
tickBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_done_white_48dp);
}

public TickedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
tickBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_done_white_48dp);
}

public void setSelected(boolean selected) {
this.selected = selected;
invalidate();
}

public boolean isSelected() {
return selected;
}

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

if(selected) {
int margin = 15;
int x = (canvas.getWidth() / 2) - (tickBmp.getWidth() / 2) - margin;
int y = (canvas.getHeight() / 2) - (tickBmp.getHeight() / 2) - margin;

canvas.drawBitmap(tickBmp, x, y, paint);
}
}
}

谢谢。

最佳答案

在 Canvas 中,在原始图像的顶部绘制另一个带有深色和一点透明度的矩形。见下文

public class TickedImageView extends ImageView {

private boolean selected = true;
private Bitmap tickBmp;
private Paint paint;
private Paint mDarkerPaint;
private int measuredWidth, measuredHeight;

public TickedImageView(Context context) {
super(context);
init();
}

public TickedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

private void init() {
paint = new Paint();
mDarkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDarkerPaint.setStyle(Paint.Style.FILL);
// Keep changing this color till it looks ok for you
mDarkerPaint.setColor(0x80142030);
tickBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_done_white_48dp);
}


public void setSelected(boolean selected) {
this.selected = selected;
invalidate();
}

public boolean isSelected() {
return selected;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);

setMeasuredDimension(measuredWidth, measuredHeight);
}

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

if (selected) {
int margin = 15;
int x = (canvas.getWidth() / 2) - (tickBmp.getWidth() / 2) - margin;
int y = (canvas.getHeight() / 2) - (tickBmp.getHeight() / 2) - margin;

canvas.drawRect(0, 0, measuredWidth, measuredHeight, mDarkerPaint);
canvas.drawBitmap(tickBmp, x, y, paint);
}
}
}

关于java - Android - 自定义 ImageView,带有勾选标记图像为选定状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30427392/

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