在没有子分类的情况下使UIView成为渐变的背景 [英] Make Background of UIView a Gradient Without Sub Classing
本文介绍了在没有子分类的情况下使UIView成为渐变的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法让UIView的背景成为渐变而不进行子类化?我宁愿不使用图像文件来实现这一点。只是为了为背景画一个渐变来创建UIView似乎很愚蠢。
Is there a way to make the background of a UIView a gradient without subclassing it? I'd rather not use an image file to accomplish this either. It just seems obtuse to have to subclass UIView just to draw a gradient for the background.
推荐答案
你可以使用 + [UIColor colorWithPatternImage:]
生成带图案的背景。示例(带上自己的CGGradient):
You can use +[UIColor colorWithPatternImage:]
to produce a patterned background. Example (bring your own 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 $ c $可能更简单c>虽然是子类。它也将使用更少的内存。
It will probably be simpler to just create a UIView
subclass though. It will use less memory as well.
这篇关于在没有子分类的情况下使UIView成为渐变的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文