Answers:
您可以使用QuartzCore并执行以下操作-
self.circleView = [[UIView alloc] initWithFrame:CGRectMake(10,20,100,100)];
self.circleView.alpha = 0.5;
self.circleView.layer.cornerRadius = 50; // half the width/height
self.circleView.backgroundColor = [UIColor blueColor];
我是否要重写drawRect方法?
是:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(ctx);
}
另外,可以在类本身内更改该视图的框架吗?
理想情况下不是,但是可以。
还是我需要从其他班级更改框架?
我让父母控制。
CGContextSetFillColorWithColor(ctx, self.colorOfCircle.CGColor);
,该解决方案中提出的方法CGColorGetComponents
仅适用于某些颜色,请参见stackoverflow.com/questions/9238743/…–
rect
,我不小心使用self.frame
了椭圆。正确的值为self.bounds
。天哪!:)
这是使用UIBezierPath的另一种方法(可能为时已晚^^),以如下方式创建一个圆并用其遮罩UIView:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor blueColor];
CAShapeLayer *shape = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:view.center radius:(view.bounds.size.width / 2) startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shape.path = path.CGPath;
view.layer.mask = shape;
layerClass
类方法以使其成为形状图层。
我对Swift扩展的贡献:
extension UIView {
func asCircle() {
self.layer.cornerRadius = self.frame.width / 2;
self.layer.masksToBounds = true
}
}
刚打电话 myView.asCircle()
masksToBounds
为true并使用self
此答案都是可选的,但这仍然是最短和最佳的解决方案
接近圆形(和其他形状)图形的另一种方法是使用蒙版。绘制圆形或其他形状的方法是,首先制作需要的形状的遮罩,其次,提供颜色的正方形,然后,将遮罩应用于这些颜色的正方形。您可以更改蒙版或颜色来获得新的自定义圆圈或其他形状。
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *area1;
@property (weak, nonatomic) IBOutlet UIView *area2;
@property (weak, nonatomic) IBOutlet UIView *area3;
@property (weak, nonatomic) IBOutlet UIView *area4;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.area1.backgroundColor = [UIColor blueColor];
[self useMaskFor: self.area1];
self.area2.backgroundColor = [UIColor orangeColor];
[self useMaskFor: self.area2];
self.area3.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:1.0];
[self useMaskFor: self.area3];
self.area4.backgroundColor = [UIColor colorWithRed: 1.0 green: 0.0 blue: 0.5 alpha:0.5];
[self useMaskFor: self.area4];
}
- (void)useMaskFor: (UIView *)colorArea {
CALayer *maskLayer = [CALayer layer];
maskLayer.frame = colorArea.bounds;
UIImage *maskImage = [UIImage imageNamed:@"cirMask.png"];
maskLayer.contents = (__bridge id)maskImage.CGImage;
colorArea.layer.mask = maskLayer;
}
@end
这是上面代码的输出:
Swift 3-Xcode 8.1
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let size:CGFloat = 35.0
myView.bounds = CGRect(x: 0, y: 0, width: size, height: size)
myView.layer.cornerRadius = size / 2
myView.layer.borderWidth = 1
myView.layer.borderColor = UIColor.Gray.cgColor
}