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

本文介绍了一个用于iOS应用的自定义UIView子类BGView,该视图实现了线性渐变背景效果。通过创建CGColorSpace并指定颜色组件来实现渐变效果,并在每个需要使用的viewController中通过resetBGView方法进行初始化。

有时候需要让整个

 

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];
}

 

转载于:https://www.cnblogs.com/moshengren/archive/2010/10/19/1855458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值