[英]Circular UIView (with cornerRadius) without Blended Layer
I'm trying to get the circle below to have an opaque solid white color where the cornerRadius cuts out the UIView. 我试图让下面的圆圈有一个不透明的纯白色,其中cornerRadius切出了UIView。
UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(i * (todaySize + rightMargin), 0, smallSize, smallSize)];
circle.layer.cornerRadius = smallSize/2;
circle.layer.borderWidth = 0.5;
circle.layer.backgroundColor = [UIColor whiteColor].CGColor;
circle.backgroundColor = [UIColor whiteColor];
[self addSubview:circle];
I've tried a few things like setting the backgroundColor and opaque without any luck. 我尝试过一些事情,比如设置backgroundColor和opaque而没有任何运气。 Color Blended Layers still shows that the surrounding of the circle is transparent. 颜色混合图层仍然显示圆圈的周围是透明的。 Does anybody know how to solve this? 有人知道如何解决这个问题吗?
To avoid blending when using rounded corners, the rounding needs to be done in drawRect, rather than as a property on the layer. 为避免在使用圆角时进行混合,需要在drawRect中进行舍入,而不是作为图层上的属性。 I needed UICollectionView cells with a rounded background in an app I'm working on. 我需要在我正在处理的应用程序中使用圆角背景的UICollectionView单元格。 When I used layer.cornerRadius, the performance took a huge hit. 当我使用layer.cornerRadius时,性能受到了极大的打击。 Turning on color blended layers yielded the following: 打开颜色混合层产生以下结果:
Not what I was hoping for, I want those cells to be colored green indicating there is no blending occurring. 不是我所希望的,我希望那些细胞是绿色的,表明没有发生混合。 To do this, I subclassed UIView into RoundedCornerView. 为此,我将UIView子类化为RoundedCornerView。 My implementation is real short and sweet: 我的实施是短暂而甜蜜的:
import UIKit
class RoundedCornerView: UIView {
static let cornerRadius = 40.0 as CGFloat
override func drawRect(rect: CGRect) {
let borderPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: RoundedCornerView.cornerRadius)
UIColor.whiteColor().set()
borderPath.fill()
}
}
Then I set the view I was rounding to be a RoundedCornerView in my nib. 然后我将我正在舍入的视图设置为我的笔尖中的RoundedCornerView。 Running at that point yielded this: 在这一点上跑步产生了这样的结果:
Scrolling is buttery smooth and there is no longer any blending occurring. 滚动是黄油平滑的,不再发生任何混合。 One odd side effect of this is that the view's backgroundColor property will color the excluded area of the corners, not the main body of the view. 一个奇怪的副作用是视图的backgroundColor属性将为角的排除区域着色,而不是视图的主体。 This means that the backgroundColor should be set to whatever is behind your view, not to the desired fill color. 这意味着backgroundColor应设置为视图后面的任何内容,而不是所需的填充颜色。
Try using a mask to both avoid blending and dealing with the parent / child background color match. 尝试使用遮罩来避免混合和处理父/子背景颜色匹配。
override func layoutSubviews() {
super.layoutSubviews()
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 20).cgPath
layer.mask = maskLayer
}
将clipsToBounds
上的clipsToBounds
或masksToBounds
上的masksToBounds
设置为YES
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.