ios - 使用 CoreGraphics 在 IOS 中使用交叉影线?

标签 ios uiview core-graphics gradient drawrect

如何使用核心图形在 IOS 中填充一个形状(应用一组 45 度的平行线)?示例代码?

(我对在 MKMapKit 中与 MKPolygon 一起使用特别感兴趣,但是目前只是想看看在 UIView 中是否可以使用 drawRect?所以用交叉线填充 UIView 的背景)

最佳答案

对于 swift 3.,使用来自@user3230875 的方法

final class CrossHatchView: UIView {
    
    // MARK: - LifeCycle
    
    override func draw(_ rect: CGRect) {

        // create rect path with bounds that equal to the 
        // size of a view, in addition it adds rounded corners, this will
        // be used later as a canvas for dash drawing
        let path:UIBezierPath = UIBezierPath(roundedRect: bounds, cornerRadius: 5)

        // specify the new area where the our drawing will be visible
        // check [link][1] for more
        path.addClip()
                
        // grab the size of drawing area
        let pathBounds = path.bounds

        // cleanUp rounded rect, that is drawn above
        // just remove roundedRect in the words
        path.removeAllPoints()

        // get start and end point of the line
        let p1 = CGPoint(x:pathBounds.maxX, y:0)
        let p2 = CGPoint(x:0, y:pathBounds.maxX)

        // draw line
        path.move(to: p1)
        path.addLine(to: p2)

        // set line width equal to double width of view
        // because we later will draw this line using dash pattern
        path.lineWidth = bounds.width * 2
        
        // set dash pattern with some interval
        let dashes:[CGFloat] = [0.5, 7.0]
        path.setLineDash(dashes, count: 2, phase: 0.0)

        // set color for line 
        UIColor.lightGray.withAlphaComponent(0.5).set()

        // actually draw a line using specific
        // color and dash pattern
        path.stroke()
    }
}

结果:

enter image description here

关于ios - 使用 CoreGraphics 在 IOS 中使用交叉影线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825095/

相关文章:

iphone - 如何在 iPhone 中停止 UIView CABasicAnimation

iOS 拖动固定到中心的形状

ios - 为了使模糊的 UIVibrancyEffect 起作用,我们是否必须将它作为单独的 View 添加到 UIBlurEffect contentView?

ios - 在 iOS 中旋转一条简单的线

ios - 在 View 变换(旋转)和调整大小(到边界)后保持自动布局

ios - CABasicAnimation - 变换比例保持在中心

ios - Firebase Facebook 登录错误 : FIRAuthErrorDomain - Unsuccessful debug_token response from Facebook

ios - 应用程序在调用 'tableView endUpdates' 时崩溃

ios - UIView 动画在 iOS 8 中无法正常工作?

iphone - 设置animationDidStopSelector : on UIView's animation delegate