如何创建圆角 UITextField 与内阴影

本文转自http://www.itstrike.cn/Question/9309fbd6-ef5d-4392-b361-a60fd0a3b18e.html

主要学习如何创建内阴影

我自定义 UITextfield ,看起来像 UISearchbar 。

像做

self.back_textfield = [[UITextField alloc]initWithFrame:CGRectMake(5, 7, 310, 30)];
[self.back_textfield setBorderStyle:UITextBorderStyleRoundedRect];
self.back_textfield.layer.cornerRadius = 15.0;

但我看到这个:

enter image description here

正如您可以看到内阴影不会按照边界。

解决方法 1:

我猜背景上 UITextField 是一个图像,所以它没有按照你的圆角半径。
创建内部阴影是 iOS 中棘手的。你有 2 个选项。
1) 使用该图像作为背景UITextField
2) 以编程方式设置阴影 (但它看起来的吸引力,比 1 选项)。

这里是从 @Matt Wilding 设置为文本字段与解决方案的圆内阴影的代码

_textField.layer.cornerRadius = 10.0f;

CAShapeLayer* shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:_textField.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:4];

// 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(_textField.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.
CGPathRef someInnerPath = [UIBezierPath bezierPathWithRoundedRect:_textField.bounds cornerRadius:10.0f].CGPath;
CGPathAddPath(path, NULL, someInnerPath);
CGPathCloseSubpath(path);

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

[[_textField layer] addSublayer:shadowLayer];

CAShapeLayer* maskLayer = [CAShapeLayer layer];
[maskLayer setPath:someInnerPath];
[shadowLayer setMask:maskLayer];

别忘了要导入

#import <QuartzCore/QuartzCore.h>
原文地址:https://www.cnblogs.com/Camier-myNiuer/p/4871592.html