gpt4 book ai didi

调用无效后,Android 自定义 View 显示纯黑色

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:32 24 4
gpt4 key购买 nike

在这段代码中,我想在两个 ImageView 的顶部之间画一条线。但是,在运行应用程序时,自定义 View 在调用 invalidate() 后显示为纯黑色。

这是我的代码:

public class ArrowView extends RelativeLayout {
public Paint paint;
public Bitmap eraser;
public Canvas cacheCanvas;

public float leftX;
public float leftY;

public float rightX;
public float rightY;

public boolean update = false;

public ImageView iv_leftArrow;
public ImageView iv_rightArrow;

private int w;
private int h;

LayoutInflater mInflater;

public ArrowView(Context context) {
super(context);
this.setWillNotDraw(false);
mInflater = LayoutInflater.from(context);
init();
}

public ArrowView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setWillNotDraw(false);
mInflater = LayoutInflater.from(context);
init();
}

public ArrowView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setWillNotDraw(false);
mInflater = LayoutInflater.from(context);
init();
}

@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
this.w = w;
this.h = h;
super.onSizeChanged(w, h, oldW, oldH);
}

public void init() {
View v = mInflater.inflate(R.layout.arrow_view, this, true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
v.setBackgroundColor(Color.TRANSPARENT);

eraser = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

iv_leftArrow = (ImageView) v.findViewById(R.id.iv_leftarrow);
iv_rightArrow = (ImageView) v.findViewById(R.id.iv_rightArrow);

cacheCanvas = new Canvas();
cacheCanvas.setBitmap(eraser);
}

public void setCoordinates(float leftX, float leftY, float rightX, float rightY) {
this.leftX = leftX;
this.leftY = leftY;
this.rightX = rightX;
this.rightY = rightY;
}

@Override
public void onDraw(Canvas c) {
super.onDraw(c);
setCoordinates(iv_leftArrow.getX() + iv_leftArrow.getWidth() / 2, iv_leftArrow.getY(), iv_rightArrow.getX() + iv_rightArrow.getWidth() / 2, iv_rightArrow.getY() );
if (update) {
c.drawLine(leftX, leftY, rightX, rightY, paint);
update = false;
}
cacheCanvas.drawPath(p, paint);
}
}

自定义 View 在调用 invalidate() 后显示为黑色是否有任何原因?

最佳答案

通常,系统会自动为您的小部件处理调整大小、隐藏、显示和大量其他事情,但如果绘制像素或支持数据的底层缓冲区已更改或陈旧(您将图像资源交换到 View 或原始数据集发生变化)。发生这种情况是因为操作系统无法知道数据以它所做的特定方式发生了变化。

在处理绘图的这些情况下,您必须使用 Widget.invalidate() 告诉系统其底层数据状态不佳,并且正如您提到的那样,重新绘图在主线程中排队.根据系统实现和 Android 版本,系统跟踪更改的内容会有所不同,但我通常做的是假设系统资源(字节数组、字符数组、资源索引、上下文中的手动绘图)未被跟踪并且需要无效其他一切都将由系统处理。

来源:When it's necessary to execute invalidate() on a View?

关于调用无效后,Android 自定义 View 显示纯黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37552011/

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