简体   繁体   English

如何在UIView中处理背景图片方向

[英]How to deal with background image orientation in UIView

I'm using setting the background image using methodology below. 我正在使用下面的方法设置背景图像。 When I rotate my device the background repeats, which make sense because it is not an image. 旋转设备时,背景会重复,这很有意义,因为它不是图像。 How do I deal with orientation change if this is the way I'm setting my background image? 如果这是我设置背景图像的方式,我该如何处理方向变化?

- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.png"]];
    self.view.backgroundColor = background;
    [background release];
}

It took me awhile to understand this concept. 我花了一段时间才了解这个概念。 I didn't want to create the same image portrait and landscape. 我不想创建相同的图像纵向和横向。 The key here is that CGAffineTransformMakeRotation rotates from the original state of your UIImageView or any UIView for that matter. 这里的关键是CGAffineTransformMakeRotation从UIImageView或任何与此相关的UIView的原始状态旋转。 This assumes your background image has orientation to it. 这假定您的背景图像已定向。 Eg You want your UIImageView to stay put, while other objects behaves to normal orientation change event. 例如,您希望UIImageView保持原状,而其他对象则表现为正常的方向更改事件。

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                duration:(NSTimeInterval)duration {

    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {  
        backgroundImage.transform = CGAffineTransformMakeRotation(M_PI / 2);
    }
    else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        backgroundImage.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    }
    else {
        backgroundImage.transform = CGAffineTransformMakeRotation(0.0);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //set the UIImageView to current UIView frame
    backgroundImage.frame = self.view.frame;
}

If I understand correctly, Your background gets created or overwritten every time you change the orientation right. 如果我理解正确,则每次更改方向权限都会创建或覆盖您的背景。 By default backgroundColor is nil . 默认情况下, backgroundColornil You can check for this, if it is nil then you go ahead and set the values. 您可以检查是否为零,然后继续设置值。 Its like 就像是

if ( self.view.backgroundColor == nil){
    //set the new values here
}   

You have to take 2 images both for horizontal and vertical and instead of allocating you can use [...: colorWithPatternImage:...]; 您必须同时拍摄2张图像的水平和垂直图像,而不是分配图像,可以使用[...: colorWithPatternImage:...]; and set it when orientation is changed to the background of the view. 并在方向更改为视图背景时进行设置。

hAPPY iCODING... 快乐编码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM