Question

I'm getting in a bit of a muddle trying to draw some paintcode graphics code in the middle of the screen horizontally.

I'm really not sure if scale or landscape orientation affects this.

I've created a UIView subclass and addSubview in viewDidLoad like so...

MenuTitleView *fancyView = [[MenuTitleView alloc] initWithFrame:self.view.bounds];
[[self view] addSubview:fancyView];

Rather than the size PaintCode gave me...

CGRect textRect = CGRectMake(0, 0, 418, 129);

I'm trying to determine the screen / view width and the size of the canvas width.

I've tried various things without success.

CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
CGFloat w = screenRect.size.width;
CGFloat width = 500;
CGFloat height = 200;
CGFloat x = (w - width) * 0.5f;
CGFloat y = 20;
CGRect textRect = CGRectMake(x, y, width, height);
Was it helpful?

Solution

Scale is not an issue, because Quartz and UIKit now work in 'points' rather than in pixels, so that's already accounted for. However orientation is not, [UIScreen mainScreen] will return the same rect either for applicationFrame or bounds etc, it's oblivious to orientation.

I like to put a solution in a category on UIView or UIViewController, because you'll reuse it plenty. something like this...

    -(CGRect )workingCanvas{

    CGRect screenRect = [UIScreen mainScreen].bounds;
    BOOL landscape = UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]);

    CGRect result = CGRectZero;

    CGFloat lesserDimension = (screenRect.size.width < screenRect.size.height) ? screenRect.size.width : screenRect.size.height;

    CGFloat greaterDimension = (screenRect.size.width > screenRect.size.height) ? screenRect.size.width : screenRect.size.height;

    result.size.width = (landscape) ? greaterDimension : lesserDimension;
    result.size.height = (landscape) ? lesserDimension : greaterDimension;

    if ([[UIApplication sharedApplication]isStatusBarVisible]){

    result.size.height -= [[UIApplication sharedApplication]statusBarFrame].size.height;
    }

return result;

}

OTHER TIPS

if you want to position your view just in the middle of the screen try this

    CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
    CGFloat width = 500;
    CGFloat height = 200;
    CGFloat x = CGRectGetMidX(screenRect);
    CGFloat y = 20;
    CGRect textRect = CGRectMake(x, y, width, height);

already tested is working

Good Luck!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top