gpt4 book ai didi

java - 如何突出显示 Canvas 上的特定矩形

转载 作者:行者123 更新时间:2023-11-30 10:59:01 25 4
gpt4 key购买 nike

根据我用于 Canvas 绘图的代码和相关的屏幕截图,我试图填充特定的红色矩形,但它不起作用。可以做些什么来确保只有顶行左数第二个矩形被填充?

enter image description here

public class Car extends View {
public Car(Context context) {
super(context);
init();
}

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

public Car(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

Paint paint;

private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(4);
// paint.setStyle(Paint.Style.STROKE); // delete line for filled rect
}

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

int w = canvas.getWidth();
int h = canvas.getHeight();

int rectWidth = w / 5;
int space = w / 15;
int topRectHeight = getPaddingTop();
int bottomRectHeight = getPaddingBottom();

for (int i = 0; i < 4; i++) {
int left = i * (rectWidth + space);
int right = left + rectWidth;

if (i == 2){
paint.setStyle(Paint.Style.STROKE); // delete line for filled rect
}

Rect rect = new Rect(left, 0, right, topRectHeight);
canvas.drawRect(rect, paint);

Rect rect2 = new Rect(left, h - bottomRectHeight, right, h);
canvas.drawRect(rect2, paint);
}
}
}

最佳答案

这样只会填充指定的矩形(只填充顶部的第二个)。

 paint.setStyle(Paint.Style.STROKE); //add this     
for (int i = 0; i < 4; i++) {
int left = i * (rectWidth + space);
int right = left + rectWidth;

if (i == 1){
paint.setStyle(Paint.Style.FILL); // change to this
}

Rect rect = new Rect(left, 0, right, topRectHeight);
canvas.drawRect(rect, paint);
paint.setStyle(Paint.Style.STROKE);//add this
Rect rect2 = new Rect(left, h - bottomRectHeight, right, h);
canvas.drawRect(rect2, paint);
}

如果你只想填充第二个底部:

 paint.setStyle(Paint.Style.STROKE); //you can remove this now    
for (int i = 0; i < 4; i++) {
paint.setStyle(Paint.Style.STROKE);//add this
int left = i * (rectWidth + space);
int right = left + rectWidth;
Rect rect = new Rect(left, 0, right, topRectHeight);
canvas.drawRect(rect, paint);

if (i == 1){
paint.setStyle(Paint.Style.FILL); // change to this
}
Rect rect2 = new Rect(left, h - bottomRectHeight, right, h);
canvas.drawRect(rect2, paint);
}

如果你想要第二个顶部和底部都填充:

paint.setStyle(Paint.Style.STROKE); //you can remove this now    
for (int i = 0; i < 4; i++) {
paint.setStyle(Paint.Style.STROKE);//add this
int left = i * (rectWidth + space);
int right = left + rectWidth;
if (i == 1){
paint.setStyle(Paint.Style.FILL); // change to this
}

Rect rect = new Rect(left, 0, right, topRectHeight);
canvas.drawRect(rect, paint);
Rect rect2 = new Rect(left, h - bottomRectHeight, right, h);
canvas.drawRect(rect2, paint);
}

关于java - 如何突出显示 Canvas 上的特定矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035710/

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