0

我在我的应用程序中动态绘制矩形,但由于某种原因没有出现右边框。其他三个边界正在出现。这是我的自定义视图代码:

private class RectView extends View{

    int leftX, rightX, topY, bottomY;
    boolean isAppt;
    private Paint rectPaint;
    private Rect rectangle;
    String time;

    public RectView(Context context, int _leftX, int _rightX, int _topY, int _bottomY,
            boolean _isAppt, String _time){
        super(context);
        leftX = _leftX;
        rightX = _rightX;
        topY = _topY;
        bottomY = _bottomY;
        isAppt = _isAppt;
        time = _time;
        init();
    }

    private void init(){

        rectPaint = new Paint();

        if(isAppt){
            rectPaint.setARGB(144, 217, 131, 121);
            rectPaint.setStyle(Style.FILL);
        }
        else{
            rectPaint.setARGB(0, 0, 0, 0);
            rectPaint.setStyle(Style.FILL);
        }
        if(leftX > rightX || topY > bottomY)
            Toast.makeText(context, "Incorrect", Toast.LENGTH_SHORT).show();
        rectangle = new Rect(leftX, topY, rightX, bottomY);

        int height = bottomY;
        int width = rightX - leftX;
        MyUtility.LogD_Common("Height = " + height + ", Width = " + width);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        params.leftMargin = leftX;
        params.rightMargin = 10;
        setLayoutParams(params);
    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawRect(rectangle, rectPaint);
        if(isAppt){
            rectPaint.setColor(Color.RED);
            rectPaint.setStrokeWidth(2);
            rectPaint.setStyle(Style.STROKE);
            canvas.drawRect(rectangle, rectPaint);
        }
    }

}

是什么导致右边框不显示?

4

1 回答 1

0

我试过你的代码,它对我来说很完美:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.addContentView(new RectView(this, 10, 100, 10, 100, true, "abcd"), new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }
}

请检查您的参数:

new RectView(this, 10, 100, 10, 100, true, "abcd")

如果您的 _righX 和 _bottomY 大于屏幕大小,则屏幕不会显示右边框:

new RectView(this, 10, 1000, 10, 1000, true, "abcd")

有一种方法可以检测屏幕大小并限制矩形大小:

int screenWidth = ((Activity)context).getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = ((Activity)context).getWindowManager().getDefaultDisplay().getHeight();

if(rightX > screenWidth)
    rightX = screenWidth;

if(bottomY > screenHeight)
    bottomY = screenHeight;

rectangle = new Rect(leftX, topY, rightX, bottomY);
于 2013-11-13T18:37:25.237 回答