开发者

Differences between drawing an Ellipse in Android and Java

In Java for some reason the Ellipse2D.Double uses the parameters (height, width, x, y) where as when I create a RectF in Android the parameters are (left, top, right, bottom) so I'm a bit confused on adjusting to the differences.

If a create an Ellipse in Java and use the following:

//Ellipse2D.Double(height, width, x, y)

x = 100;
y = 120;
centerX = getWidth() / 2;
centerY = getHeight() / 2;

//Ellipse2D.Double(100, 120, (centerX - 100) * 2, (centerY - 120) * 2);
new Ellipse2D.Double(x, y, (centerX - x) * 2, (centerY - y) * 2);

Would this be equivalent for Android:

//RectF(left, top, right, bottom)

x = 100;
y = 120;
centerX = getWidth() / 2;
centerY = getHeight() / 2;

new RectF((centerX - 100) * 2, (centerY - 120) * 2), 120 - ((centerX - 100) * 2), 100 - ((centerY -120) * 2); 

//canvas.drawOval(myRectF, paint);

I'm not quite sure if they are equivalent, and am wondering if I am calculating it correctly?

Alternatively, can one override the RectF to make it simliar to how Ellipse2D? Ie. change the parameters to work with height and width r开发者_StackOverflowather than right and bottom?


For the override part, I don't thing it would be a good idea since RectF isn't only used for ellipses.

you can easily write a method that draw the Oval by passing the data the way you prefer...

something like:

public RectF myOval(float width, float height, float x, float y){
    float halfW = width / 2;
    float halfH = height / 2;
    return new RectF(x - halfW, y - halfH, x + halfW, y + halfH);
}

canvas.drawOval(myOval(width, height, x, y), paint);


To keep in the x, y, width, height thinking, you can construct a utility function to build a RectF with the coordinates in the order you like to think of them:

public static RectF buildRectF(double x, double y, double width, double height) {
    // r(l, t, r, b)
    RectF rectf = new RectF(x - width / 2, y - height / 2, x + width / 2, y + height / 2);
    return rectf;
}

It is unclear what you are trying to do with the code sample you have. Ellipse2D.Double takes 4 parameters: x, y, width and height. It looks like you are setting width to be (centerX - x) * 2; this will ensure that the width is twice the distance from the center of the component your code resides in to the point (100, 120), if the center is to the right of the point (100, 120). If your component gets too small, though, you will assign a negative width, which could be awkward.

Also, you are using hardcoded values in your RectF example, and combining 120 (the y?) and 100 (the x?) in the same arguments to RectF, which is most likely not what you want to do.

I'd suggest drawing a picture on a piece of paper, label the coordinates with the values you think they should be, then write your code. You should be able to more clearly see what your top left bottom and right (or x, y, width and height) values should be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜