我想为UITextView应用渐变效果。这是我的代码:
textView = [[UITextView alloc]initWithFrame:CGRectMake(50,220,self.view.frame.size.width-100,self.view.frame.size.height-300)];
underTextView = [[UIView alloc]initWithFrame:CGRectMake(50,220,self.view.frame.size.width-100,self.view.frame.size.height-300)];
CGFloat layerWidth = 8.f;
CAGradientLayer *gl1 = [CAGradientLayer layer];
id col1 = (id)[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0]CGColor];
id col2 = (id)[[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]CGColor];
gl1.colors = @[col2, col1, col1, col2];
if (self.textView.contentOffset.y < 5)
gl1.locations = @[@0.0, @0.0, @0.85, @1.0];
if (self.textView.contentOffset.y >=5 && self.textView.contentOffset.y < 20) {
CGFloat number = (self.textView.contentOffset.y - 5) * 0.01;
gl1.locations = @[@0.0, [NSNumber numberWithFloat:number], @0.85, @1.0];
}
if (self.textView.contentOffset.y >= 20 && self.textView.contentOffset.y < self.textView.contentSize.height - self.textView.frame.size.height - 20)
gl1.locations = @[@0.0, @0.15, @0.85, @1.0];
if (self.textView.contentOffset.y >= (self.textView.contentSize.height - self.textView.frame.size.height - 20) && self.textView.contentOffset.y < (self.textView.contentSize.height - self.textView.frame.size.height - 5)) {
CGFloat number = 1 - (self.textView.contentSize.height - self.textView.contentOffset.y - self.textView.frame.size.height - 5) * 0.01;
gl1.locations = @[@0.0, @0.15, [NSNumber numberWithFloat:number], @1.0];
}
if (self.textView.contentOffset.y >= self.textView.contentSize.height - self.textView.frame.size.height - 5)
gl1.locations = @[@0.0, @0.15, @1.0, @1.0];
gl1.frame = CGRectMake(0, 0, self.underTextView.frame.size.width - layerWidth, self.underTextView.frame.size.height);
CAGradientLayer *gl2 = [CAGradientLayer layer];
gl2.colors = @[col1, col1];
gl2.locations = @[@0.0, @1.0];
gl2.frame = CGRectMake(self.underTextView.frame.size.width - layerWidth, 0, layerWidth, self.underTextView.frame.size.height);
CAGradientLayer *gl = [CAGradientLayer layer];
[gl addSublayer:gl1];
[gl addSublayer:gl2];
self.underTextView.layer.mask = gl;
[self.underTextView addSubview:textView];
[self.view addSubview:underTextView];
但是没有应用渐变效果。有人可以说明错误的地方。任何想法都会发生。
谢谢,
答案 0 :(得分:0)
但为什么不添加带有在photoshop中创建的渐变的背景图像? 以编程方式创建渐变会影响性能,因此我认为最好将UIImageView添加为textview的背景,并将textView.backgroundColor设置为[UIColor clearColor];
答案 1 :(得分:0)
你可以简单地替换
self.underTextView.layer.mask = gl;
到
[[underTextView layer] addSublayer:gl];
它可能有用。