使 UIView 的背景成为没有子类的渐变 [英] Make Background of UIView a Gradient Without Sub Classing

查看:14
本文介绍了使 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 子类可能会更简单.它也会使用更少的内存.

It will probably be simpler to just create a UIView subclass though. It will use less memory as well.

这篇关于使 UIView 的背景成为没有子类的渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆