使UIView的背景成为没有子分类的梯度

mac*_*osh 27 iphone subclass uiview

有没有办法让UIView的背景成为渐变而不进行子类化?我宁愿不使用图像文件来实现这一点.只是为了为背景绘制渐变而必须将UIView子类化似乎很愚蠢.

rpe*_*ich 33

您可以使用+[UIColor colorWithPatternImage:]生成图案背景.示例(带上您自己的CGGradient):

// Allocate color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Allocate bitmap context
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, 320, 480, 8, 4 * 320, colorSpace, kCGImageAlphaNoneSkipFirst);
//allocate myGradient
CGFloat locationList[]  = {0.0f, 1.0f};
CGFloat colorList[]     = {0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f};
CGGradientRef myGradient   = CGGradientCreateWithColorComponents(colorSpace, colorList, locationList, 2);
// Draw Gradient Here
CGContextDrawLinearGradient(bitmapContext, myGradient, CGPointMake(0.0f, 0.0f), CGPointMake(320.0f, 480.0f), 0);
// Create a CGImage from context
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
// Create a UIImage from CGImage
UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
// Release the CGImage
CGImageRelease(cgImage);
// Release the bitmap context
CGContextRelease(bitmapContext);
// Release the color space
CGColorSpaceRelease(colorSpace);
// Create the patterned UIColor and set as background color
[targetView setBackgroundColor:[UIColor colorWithPatternImage:image]];
Run Code Online (Sandbox Code Playgroud)

UIView尽管创建一个子类可能更简单.它也将使用更少的内存.


kej*_*eji 29

你可以这样做:

Swift> = 4.0:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.white.cgColor]
view.layer.insertSublayer(gradient, at: 0)
Run Code Online (Sandbox Code Playgroud)

Swift 3.0:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.red().cgColor, UIColor.white().cgColor]
view.layer.insertSublayer(gradient, at: 0)
Run Code Online (Sandbox Code Playgroud)

斯威夫特<= 2.3:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.redColor().CGColor, UIColor.whiteColor().CGColor]
view.layer.insertSublayer(gradient, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)

Objective-C的:

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.view.layer insertSublayer:gradient atIndex:0];
Run Code Online (Sandbox Code Playgroud)

确保将QuartzCore框架添加到您的项目中(至少对于Objective-C)...

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)