目前正在使用:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
但问题在于它在垂直和水平方向上都重复出现。我想让它在水平方向上重复出现,同时在垂直方向上拉伸以适应屏幕。
目前正在使用:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
但问题在于它在垂直和水平方向上都重复出现。我想让它在水平方向上重复出现,同时在垂直方向上拉伸以适应屏幕。
创建一个名为BackgroundImageView的UIView子类,重写drawInRect方法:
import UIKit
@IBDesignable
class BackgroundImageView: UIView {
@IBInspectable var backgroundImage:UIImage?{
didSet{
self.setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
var i:CGFloat = 0.0
if backgroundImage != nil
{
while (i*backgroundImage!.size.width)<self.bounds.size.width
{
backgroundImage!.drawInRect(CGRect(x: i*backgroundImage!.size.width, y: 0.0, width: backgroundImage!.size.width, height: self.bounds.size.height))
i+=1.0
}
}
}
}
在IB中拖出一个UIView,将其类更改为BackgroundImageView,并将backgroundImage设置为background.png。
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenHeight = screenRect.size.height;
UIImage * targetImage = [UIImage imageNamed:@"background.png"];
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, targetImage.size.width, screenHeight)];
// redraw the image
UIGraphicsBeginImageContextWithOptions(yourView.frame.size, NO, 0.f);
[targetImage drawInRect:CGRectMake(0.f, 0.f, targetImage.size.width, screenHeight)];
UIImage * resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view setBackgroundColor:[UIColor colorWithPatternImage:resultImage]];