开发者

centering a CGRect in a view

I have an image displaying in a CGRect. how do I center the rect in the view?

here's my code:

UIImage * image = [UIImage imageNamed:place.imag开发者_如何学JAVAe];
CGRect rect = CGRectMake(10.0f, 90.0f, image.size.width, image.size.height);

UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect];
[imageView setImage:image];

I've tried imageView.center but to no effect.

thanks in advance.


Looking at:

https://developer.apple.com/documentation/coregraphics/cggeometry

You can do:

CGPoint center = CGPointMake(CGRectGetMidX(mainRect), CGRectGetMidY(mainRect));


UIView's center is a property, not a method.

You need to calculate the actual location you want to put it in. You can do this by setting the frame of the view, or by setting its center, which is simpler in your case.

You don't say what view you then go make imageView a subview of. If you're putting it inside something called superview, you could do this:

CGPoint superCenter = CGPointMake(CGRectGetMidX([superview bounds]), CGRectGetMidY([superview bounds]));
[imageView setCenter:superCenter];


Position the imageView in the parentView based on the size and origin of the parentView's rect.

Given a parent view named parentView:

float parentRect = parentView.frame;
float imageRect = imageView.frame;

imageRect.origin.x = (int)(parentView.origin.x + (parentRect.size.width - imageRect.size.width) / 2);
imageRect.origin.y = (int)(parentView.origin.y + (parentRect.size.height- imageRect.size.height) / 2);
imageView.frame = imageRect;

Casting the origins to int ensures that your centered image is not blurry (though it may be off center by a subpixel amount).


CGRect r = thingToCenter.frame;
r.origin = parentView.bounds.origin;
r.origin.x = parentView.bounds.size.width / 2  - r.size.width / 2;
r.origin.y = parentView.bounds.size.height / 2  - r.size.height / 2 + 12;
thingToCenter.frame = r;


CGRect CGRectIntegralCenteredInRect(CGRect innerRect, CGRect outerRect) {
    CGFloat originX = outerRect.origin.x + ((outerRect.size.width - innerRect.size.width) * 0.5f);
    CGFloat originY = outerRect.origin.y + ((outerRect.size.height - innerRect.size.height) * 0.5f);
    return CGRectIntegral(CGRectMake(originX, originY, innerRect.size.width, innerRect.size.height));
}


For Swift 4:

CGPoint center = CGPoint(x: buttonRect.midX, y: buttonRect.midY)


If the function is called frequently, you can also use macros as shown here for simplicity.

#define Center(x) CGPointMake(CGRectGetMidX(x), CGRectGetMidY(x));

Then use it like

CGPoint myPoint = Center(myRect);


Swift 4

let center = CGPoint(x: bounds.midX, y: bounds.midY)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜