UITextView内部阴影

时间:2014-05-18 17:43:29

标签: ios objective-c

我试图仅在UITextView的顶部创建内部阴影,但我遇到了一些困难。我从this帖子借了代码,但我并不清楚究竟发生了什么。

CAShapeLayer* shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:[self bounds]];

// Standard shadow stuff
[shadowLayer setShadowColor:[[UIColor colorWithWhite:0 alpha:1] CGColor]];
[shadowLayer setShadowOffset:CGSizeMake(0.0f, 0.0f)];
[shadowLayer setShadowOpacity:1.0f];
[shadowLayer setShadowRadius:5];

// Causes the inner region in this example to NOT be filled.
[shadowLayer setFillRule:kCAFillRuleEvenOdd];

// Create the larger rectangle path.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectInset(bounds, -42, -42));

// Add the inner path so it's subtracted from the outer path.
// someInnerPath could be a simple bounds rect, or maybe
// a rounded one for some extra fanciness.
CGPathAddPath(path, NULL, someInnerPath);
CGPathCloseSubpath(path);

[shadowLayer setPath:path];
CGPathRelease(path);

[[self layer] addSublayer:shadowLayer];

究竟是什么" someInnerPath"如果我只想在矩形UITextView的顶部设置一个简单的阴影(我不需要圆角效果)。

1 个答案:

答案 0 :(得分:1)

请在viewDidLoad或最适合您的地方尝试此操作:

CGFloat inset = -20;

UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(inset, 0,
                                                                       self.textView.bounds.size.width - inset - inset,
                                                                       self.textView.bounds.size.height)];

UIView *overlayView = [[UIView alloc]initWithFrame:self.textView.frame];
overlayView.userInteractionEnabled = NO;
overlayView.clipsToBounds = YES;

CALayer *layer = overlayView.layer;
layer.shadowPath = shadowPath.CGPath;
layer.shadowColor = [UIColor colorWithWhite:0.0 alpha:1.0].CGColor;
layer.shadowOpacity = 1.0;
layer.shadowRadius = 10;
layer.shadowOffset = CGSizeMake(0, self.textView.bounds.size.height * -1);

[self.view addSubview:overlayView];

插图是为了确保阴影不会在角落之前停止。尝试将其设置为零,你会明白我的意思。

基本上代码正在做的是创建一个视图,其图层的阴影偏移到视图的顶部。我尝试将overlayView直接添加到textView中,但是它会更加坚持滚动,所以当我向下滚动时,会出现一个大黑盒子。将overlayView添加到self.view可以解决问题。

您可能想要根据自己的喜好使用shadowColor,shadowOpacity和shadowRadius参数。