【问题标题】:Draw rectangle multiple times in new position not working在新位置多次绘制矩形不起作用
【发布时间】:2012-08-09 19:13:13
【问题描述】:

每次我用这段代码创建一个新的矩形时,它都不起作用,我只能绘制到指定的位置,如果我在执行时使用变量来改变位置,它不会绘制任何东西。

在 Asynctask 方法中:

rect = new desenho(main.this, x, y);
        

这叫这个:

public class desenho extends View{
    
    int x, y;
    Paint mPaint = new Paint();
    
    public desenho(Context context, int x, int y) {
        super(context);
        this.x = x;
        this.y = y;
        mPaint.setStrokeWidth(3);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLACK);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(width, y);
    }
    
    @Override
    protected void onDraw(Canvas c) {
        // TODO Auto-generated method stub
        super.onDraw(c);
        c.drawRect(5, y, width-5, y+x, mPaint);
    }
}

【问题讨论】:

  • 你的背景不是黑色的吧? :)。看起来您可能正在黑色背景上绘制黑色矩形。您也可以尝试使用调试器单步执行代码,以查看调用 drawRect 时的值。
  • 在这种情况下它不绘制任何东西,只有我这样做:c.drawRect(5, 5, width-5, 100, mPaint);
  • 没有背景是白色的,我检查了 system.out 上的值,它们是正确的..我不知道出了什么问题......也许原因是 AsyncTaskMethod ?

标签: android dynamic android-asynctask draw shapes


【解决方案1】:

在我看来,您希望大小与位置无关。为此,您的 Canvas.drawRect(left, top, right, bottom, paint) 必须满足这些要求:

  • 左 - 右 = 一个
  • 顶部 - 底部 = b

其中 a、b 是常数。示例:

c.drawRect(xPos, yPos, xPos + width - 1, yPos + height - 1, mPaint);

你在这个例子中看到

  • 左 - 右 = xPos - (xPos + 宽度 - 1) = 1 - 宽度
  • 顶部 - 底部 = yPos - (yPos + height - 1) = 1 - height

两者都是恒定的→大小是恒定的。

【讨论】:

  • 感谢您的回复。但是,如果我理解正确我正在这样做,我只会更改矩形的顶部和底部坐标,并且它们始终是一个常数。当我回到家时,我会深入分析你的答案。
  • 看来你是对的。乍一看,我认为作为底部参数的一部分的 x 是指一些水平属性,但现在我发现它确实是常量。
  • 顺便说一下,最右边的像素的索引宽度为1,所以如果你想让你的矩形居中,宽度5应该是宽度6
  • @ Joel Sjögren,当我用这个创建一系列矩形时: c.drawRect(5, top, width-5, top+bottom, mPaint);它不起作用(第一张图片)。但如果我只创建一个: c.drawRect(5, 5, width-5, 5+bottom, mPaint);它有效(第二张图片)。似乎原因是在运行时递增的顶部变量... 图片:imgur.com/a/xfJYj
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多