有没有办法使 UIView 的背景成为渐变而不对其进行子类化?我也不想使用图像文件来完成此任务。仅仅为了绘制背景渐变而必须子类化 UIView 似乎很愚蠢。
最佳答案
您可以使用+[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]];
不过,创建一个 UIView
子类可能会更简单。它也会使用更少的内存。
关于iphone - 使 UIView 的背景成为渐变而不使用子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/844710/