如何实现 画一个屏幕的渐变效果,并将其作为程序的背景模板

有时候需要让整个

 

BgEngine.h

 

#import <UIKit/UIKit.h>

@interface BGView : UIView
{
	
	CGGradientRef gradient;
}

@end

 

BgEngine.m

 

#import "BgEngine.h"

@implementation BGView

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	if(self != nil)
	{
		CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
		CGFloat colors[] =
		{
			243.0 / 255.0, 181.0 / 255.0, 206.0 / 255.0, 1.00,
			207.0 / 255.0, 170.0 / 255.0, 185.0 / 255.0, 1.00,
		};
		gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
		CGColorSpaceRelease(rgb);
	}
	return self;
}

- (void)dealloc{
	CFRelease(gradient);
	[super dealloc];
}

// Returns an appropriate starting point for the demonstration of a linear gradient
CGPoint demoLGStart(CGRect bounds)
{
	return CGPointMake(bounds.origin.x, bounds.origin.y);
}

// Returns an appropriate ending point for the demonstration of a linear gradient
CGPoint demoLGEnd(CGRect bounds)
{
	return CGPointMake(bounds.origin.x, bounds.origin.y + bounds.size.height);
}

- (void)drawRect:(CGRect)rect{
	CGPoint start, end;
	
	CGContextRef context = UIGraphicsGetCurrentContext();
	
	CGContextSaveGState(context);
	CGContextClipToRect(context, rect);
	
	start = demoLGStart(rect);
	end = demoLGEnd(rect);
	CGContextDrawLinearGradient(context, gradient, start, end, 0);
	CGContextRestoreGState(context);
}

@end

 

 

在每个需要使用的viewController里面veiwDidLoad函数里面添加如下代码:

 

使用的时候:
- (void)resetBGView{
	CGRect appFrame = [UIScreen mainScreen].applicationFrame;
	CGRect bgframe = CGRectMake(0, 44 + 20, appFrame.size.width, appFrame.size.height - 44 - 48);//按世纪需求来定
	BGView *bgView = [[BGView alloc] initWithFrame:bgframe];
	[window insertSubview:bgView atIndex:0];
	[bgView release];
}

 

posted @ 2010-10-19 12:32  苏瑞强  阅读(845)  评论(0编辑  收藏  举报