ios – 如何使用蒙版为圆形图像添加边框

ios – 如何使用蒙版为圆形图像添加边框,第1张

概述这是我的尝试: func round() { let width = bounds.width < bounds.height ? bounds.width : bounds.height let mask = CAShapeLayer() mask.path = UIBezierPath(ovalInRect: CGRectMake(bounds.midX - width 这是我的尝试:

func round() {    let wIDth = bounds.wIDth < bounds.height ? bounds.wIDth : bounds.height    let mask = CAShapeLayer()    mask.path = UIBezIErPath(ovalInRect: CGRectMake(bounds.mIDX - wIDth / 2,bounds.mIDY - wIDth / 2,wIDth,wIDth)).CGPath    self.layer.mask = mask    // add border    let frameLayer = CAShapeLayer()    frameLayer.path = mask.path    frameLayer.linewidth = 4.0    frameLayer.strokecolor = UIcolor.whitecolor().CGcolor    frameLayer.fillcolor = nil    self.layer.addSublayer(frameLayer)}@H_419_12@  

它适用于iphone 6模拟器(故事板的大小为4.7),但在5s和6它看起来很奇怪:

这是一个自动布局问题吗?没有边框,自动布局工作正常.这是我第一次使用面具,所以我不确定我所做的是否正确.

在vIEwDIDLayoutSubvIEws中调用round函数.

有什么想法吗?

解决方法 例如,如果你有子类UIImageVIEw,你可以覆盖layoutSubvIEws,以便它(a)更新掩码; (b)删除任何旧边界; (c)增加新的边界.在Swift 3中:

import UIKit@IBDesignableclass RoundedImageVIEw: UIImageVIEw {    /// saved rendition of border layer    private weak var borderLayer: CAShapeLayer?    overrIDe func layoutSubvIEws() {        super.layoutSubvIEws()        // create path        let wIDth = min(bounds.wIDth,bounds.height)        let path = UIBezIErPath(arcCenter: CGPoint(x: bounds.mIDX,y: bounds.mIDY),radius: wIDth / 2,startAngle: 0,endAngle: .pi * 2,clockwise: true)        // update mask and save for future reference        let mask = CAShapeLayer()        mask.path = path.cgPath        layer.mask = mask        // create border layer        let frameLayer = CAShapeLayer()        frameLayer.path = path.cgPath        frameLayer.linewidth = 32.0        frameLayer.strokecolor = UIcolor.white.cgcolor        frameLayer.fillcolor = nil        // if we had prevIoUs border remove it,add new one,and save reference to new one        borderLayer?.removeFromSuperlayer()        layer.addSublayer(frameLayer)        borderLayer = frameLayer    }}@H_419_12@  

这样,它会响应布局的变化,但它确保清理任何旧边框.

顺便说一句,如果你不是UIImageVIEw的子类,而是将这个逻辑放在视图控制器中,你将覆盖vIEwWillLayoutSubvIEws而不是UIVIEw的layoutSubvIEws.但基本的想法是一样的.

顺便说一下,我将一个蒙版与这个形状图层结合使用,因为如果你只是应用UIVIEw的圆角,它会导致奇怪的瑕疵(看看圆形边框下部非常细的灰线):

如果使用bezIEr路径方法,则不会产生此类工件:

有关Swift 2.3示例,请参阅earlier revision of this answer.

总结

以上是内存溢出为你收集整理的ios – 如何使用蒙版为圆形图像添加边框全部内容,希望文章能够帮你解决ios – 如何使用蒙版为圆形图像添加边框所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1005083.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存