如何在 Swift iOS Playground 上制作带有圆角的 UIImageView?
里面需要填充颜色。
9 回答
let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
imageView.backgroundColor = UIColor.redColor()
imageView.layer.cornerRadius = 8.0
imageView.clipsToBounds = true
结果:
对于 swift 中的圆形图像框架,它对我有用的是:
self.profileImageView.image = UIImage(named:"profileUser")
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
self.profileImageView.clipsToBounds = true
并添加阴影:
self.profileImageView.layer.masksToBounds = NO;
self.profileImageView.layer.cornerRadius = 8;
self.profileImageView.shadowOffset = CGSizeMake(5.0, 5.0);
self.profileImageView.shadowRadius = 5;
self.profileImageView.shadowOpacity = 0.5;
试试这个,它对我有用。
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
self.profileImageView.clipsToBounds = true
我厌倦了为每个 UIView编写设置半径和掩码。所以我对 UIView 做了以下扩展。应该适用于每个 UIView 子类,虽然我没有测试过。当然,可以针对您使用的特定视图缩小扩展范围。
extension UIView {
func setRadius(radius: CGFloat? = nil) {
self.layer.cornerRadius = radius ?? self.frame.width / 2;
self.layer.masksToBounds = true;
}
}
如果您不传递任何特定值,它将默认为视图的半宽度。
如果您想选择对每个进行舍UIImageView
入,您可以将此代码复制到您的项目中,而不会忘记检查clip to bounds
并将其值设置为true
import UIKit
@IBDesignable
extension UIImageView
{
private struct AssociatedKey
{
static var rounded = "UIImageView.rounded"
}
@IBInspectable var rounded: Bool
{
get
{
if let rounded = objc_getAssociatedObject(self, &AssociatedKey.rounded) as? Bool
{
return rounded
}
else
{
return false
}
}
set
{
objc_setAssociatedObject(self, &AssociatedKey.rounded, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
layer.cornerRadius = CGFloat(newValue ? 1.0 : 0.0)*min(bounds.width, bounds.height)/2
}
}
}
斯威夫特 5.0:
我个人的偏好是为像这样的特定更改提供一个额外的 swift 文件。然后我要做的是创建一个类,例如“RoundCorner”,它是我想要在这种情况下更改为 View 元素的元素的子类。然后我将覆盖各个设置。
class RoundCorner: UIView {
override func draw(_ rect: CGRect) {
self.layer.cornerRadius = 10 // change this number to get the corners you want
self.layer.masksToBounds = true
}
}
之后,您只需选择要更改的元素,并将自定义类设置为我们之前创建的类。
在身份检查器的用户定义的运行时属性部分设置layer.cornerRadius = 10甚至适用于表格单元格等可重复元素。
在 Swift 4 中,你可以很容易地做到这一点:
yourUIImage.layer.cornerRadius = 10 // Set it how you prefer
yourUIImage.layer.masksToBounds = true
如果您使用相当长的矩形图像,例如用于应用程序中的特色内容部分或其他任何内容,请确保将Content Mode
其设置为Scale To Fit
,否则角落会以某种方式变圆但会严重切割并且不会是完美的圆角而是在它夹住的地方进行圆形,然后是锐利的切割。