边框的右侧没有绘图

时间:2013-11-13 17:57:05

标签: android shapes

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

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);
        }
    }

}

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

1 个答案:

答案 0 :(得分: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);