점선(점선 아님!) 선 그리기, 2017년 IBDesignable
UIKit으로 점선을 그리기 쉽습니다.그래서:
CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];
진짜 점선을 그릴 수 있는 방법은 없나요?
라인 캡 스타일을 둥글게 설정하고 "on" 길이를 작은 숫자로 설정합니다.
신속한 운동장 예:
import UIKit
import PlaygroundSupport
let path = UIBezierPath()
path.move(to: CGPoint(x:10,y:10))
path.addLine(to: CGPoint(x:290,y:10))
path.lineWidth = 8
let dashes: [CGFloat] = [0.001, path.lineWidth * 2]
path.setLineDash(dashes, count: dashes.count, phase: 0)
path.lineCapStyle = CGLineCap.round
UIGraphicsBeginImageContextWithOptions(CGSize(width:300, height:20), false, 2)
UIColor.white.setFill()
UIGraphicsGetCurrentContext()!.fill(.infinite)
UIColor.black.setStroke()
path.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
let view = UIImageView(image: image)
PlaygroundPage.current.liveView = view
UIGraphicsEndImageContext()
결과:
objective-C의 경우 문제와 동일한 예제 클래스를 사용하여 간단히 추가합니다.
CGContextSetLineCap(cx, kCGLineCapRound);
에 전화하기 전에CGContextStrokePath
, 그리고 변경.ra
내 스위프트 코드와 일치하는 배열 값.
위의 Swift 예제의 Objective-C 버전:
UIBezierPath * path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(10.0, 10.0)];
[path addLineToPoint:CGPointMake(290.0, 10.0)];
[path setLineWidth:8.0];
CGFloat dashes[] = { path.lineWidth, path.lineWidth * 2 };
[path setLineDash:dashes count:2 phase:0];
[path setLineCapStyle:kCGLineCapRound];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 20), false, 2);
[path stroke];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
스위프트 3.0과 호환되는 UIView 확장을 사용하면 다음이 작동합니다.
extension UIView {
func addDashedBorder(strokeColor: UIColor, lineWidth: CGFloat) {
self.layoutIfNeeded()
let strokeColor = strokeColor.cgColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = strokeColor
shapeLayer.lineWidth = lineWidth
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = [5,5] // adjust to your liking
shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: shapeRect.width, height: shapeRect.height), cornerRadius: self.layer.cornerRadius).cgPath
self.layer.addSublayer(shapeLayer)
}
}
그 다음에 실행되는 함수에서viewDidLoad
,맘에 들다viewDidLayoutSubviews
, 운영을 맡다addDashedBorder
해당 뷰에서 기능:
class ViewController: UIViewController {
var someView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
someView = UIView()
someView.layer.cornerRadius = 5.0
view.addSubview(someView)
someView.translatesAutoresizingMaskIntoConstraints = false
someView.widthAnchor.constraint(equalToConstant: 200).isActive = true
someView.heightAnchor.constraint(equalToConstant: 200).isActive = true
someView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
someView.addDashedBorder(strokeColor: UIColor.red, lineWidth: 1.0)
}
}
안녕 얘들아 이 솔루션은 나에게 잘 작동했습니다.콘솔 경고를 방지하기 위해 어딘가를 찾아서 조금 바꿨습니다.
extension UIImage {
static func drawDottedImage(width: CGFloat, height: CGFloat, color: UIColor) -> UIImage {
let path = UIBezierPath()
path.move(to: CGPoint(x: 1.0, y: 1.0))
path.addLine(to: CGPoint(x: width, y: 1))
path.lineWidth = 1.5
let dashes: [CGFloat] = [path.lineWidth, path.lineWidth * 5]
path.setLineDash(dashes, count: 2, phase: 0)
path.lineCapStyle = .butt
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 2)
color.setStroke()
path.stroke()
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
결과는 다음과 같습니다.
점선을 쉽게 사용자 정의하기 위해 rob mayoff 수용된 솔루션에 대해 약간의 작업을 수행합니다.
- 각 원의 반지름을 바꿉니다.
- 두 원 사이의 간격을 바꿉니다.
- 생성할 패턴 수를 변경합니다.
이 기능은 UII 메시지를 반환합니다.
extension UIImage {
class func dottedLine(radius radius: CGFloat, space: CGFloat, numberOfPattern: CGFloat) -> UIImage {
let path = UIBezierPath()
path.moveToPoint(CGPointMake(radius/2, radius/2))
path.addLineToPoint(CGPointMake((numberOfPattern)*(space+1)*radius, radius/2))
path.lineWidth = radius
let dashes: [CGFloat] = [path.lineWidth * 0, path.lineWidth * (space+1)]
path.setLineDash(dashes, count: dashes.count, phase: 0)
path.lineCapStyle = CGLineCap.Round
UIGraphicsBeginImageContextWithOptions(CGSizeMake((numberOfPattern)*(space+1)*radius, radius), false, 1)
UIColor.whiteColor().setStroke()
path.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
이미지를 얻는 방법은 다음과 같습니다.
UIImage.dottedLine(radius: 100, space: 2, numberOfPattern: 1)
완전한 답변이 아니라 제임스 P가 가장 좋아하는 답변에 대한 논평에서 제기한 매우 중요한 답변일 뿐입니다.
그는 이렇게 썼습니다.
온 길이를 0.01로 설정하면 원형의 점이 나오는데, 0을 사용하면 약간 길쭉합니다.
예를들면,
let dashes: [CGFloat] = [0.001, path.lineWidth * 2]
스위프트 3.1에서는 아래 코드를 사용할 수 있습니다.
context.setLineCap(.round)
세 가지 스타일이 있습니다.
/* Line cap styles. */
public enum CGLineCap : Int32 {
case butt
case round
case square
}
아래 코드로 잘 작동하고 있습니다.
layer.path = linePath.cgPath
layer.lineWidth = 3
layer.lineDashPattern = [1,layer.lineWidth*2] as [NSNumber]
layer.lineCap = "round"
이 질문에 대답하기에는 너무 늦었을 수도 있습니다. 하지만 동의하신다면 앞으로 그 문제에 직면하게 될 개발자들에게 이 문제를 해결할 수 있는 쉬운 방법을 공유하고 싶습니다.@IBDesignable을 사용하는 가장 쉬운 솔루션이라고 생각합니다.당신은 단지 그 클래스를 만들기만 하면 됩니다.
import UIKit
@IBDesignable class DottedVertical: UIView {
@IBInspectable var dotColor: UIColor = UIColor.red
@IBInspectable var lowerHalfOnly: Bool = false
override func draw(_ rect: CGRect) {
// say you want 8 dots, with perfect fenceposting:
let totalCount = 8 + 8 - 1
let fullHeight = bounds.size.height
let width = bounds.size.width
let itemLength = fullHeight / CGFloat(totalCount)
let path = UIBezierPath()
let beginFromTop = CGFloat(0.0)
let top = CGPoint(x: width/2, y: beginFromTop)
let bottom = CGPoint(x: width/2, y: fullHeight)
path.move(to: top)
path.addLine(to: bottom)
path.lineWidth = width
//DASHED SIMPLE LINE
//let dashes: [CGFloat] = [itemLength, itemLength]
//path.setLineDash(dashes, count: dashes.count, phase: 0)
// for ROUNDED dots, simply change to....
let dashes: [CGFloat] = [0.0, itemLength * 1.1]
path.lineCapStyle = CGLineCap.round
path.setLineDash(dashes, count: dashes.count, phase: 0)
dotColor.setStroke()
path.stroke()
}
}
그런 다음 스토리보드에 이를 추가합니다.
콜드 작업을 마치면 이 선에서 레이어 사이의 공간을 사용자 지정합니다.let dashes: [CGFloat] = [0.0, itemLength * 1.1]
--> 점선 수직 클래스의 39번째 줄입니다.또는 스토리보드에서 선 보기 너비를 편집하기 위해 필요한 레이어 너비를 사용자 지정하려면
CASHapeLayer 및 CGMutablePath를 사용하여 수직 또는 수평 대시/점선 작성
func drawDottedLine(dashColor:UIColor,linePattern:[NSNumber] = [2,2],lineWidth:CGFloat = 1, orientation: Orientation = .horizontal, shape: Shape = .line) {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = dashColor.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.lineDashPattern = linePattern
if shape == .round {
shapeLayer.lineCap = .round
}
let path = CGMutablePath()
if orientation == .vertical {
path.addLines(between: [CGPoint(x: lineWidth/2, y: lineWidth/2),
CGPoint(x: lineWidth/2, y: self.frame.height)])
} else {
path.addLines(between: [CGPoint(x: lineWidth/2, y: lineWidth/2),
CGPoint(x: self.frame.width, y: lineWidth/2)])
}
shapeLayer.path = path
layer.addSublayer(shapeLayer)
}
는 했습니다 과 같은 했습니다.titleLabel
(UILabel
)에서viewDidAppear
:
CAShapeLayer *shapelayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0, titileLabel.frame.size.height-2)];
[path addLineToPoint:CGPointMake(SCREEN_WIDTH, titileLabel.frame.size.height-2)];
UIColor *fill = [UIColor colorWithRed:0.80f green:0.80f blue:0.80f alpha:1.00f];
shapelayer.strokeStart = 0.0;
shapelayer.strokeColor = fill.CGColor;
shapelayer.lineWidth = 2.0;
shapelayer.lineJoin = kCALineJoinRound;
shapelayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:3 ], nil];
shapelayer.path = path.CGPath;
[titileLabel.layer addSublayer:shapelayer];
참조 : https://gist.github.com/kaiix/4070967
언급URL : https://stackoverflow.com/questions/26018302/draw-dotted-not-dashed-line-with-ibdesignable-in-2017
'sourcecode' 카테고리의 다른 글
Oracle 별칭 이해 - 두 번째 쿼리로 래핑하지 않는 한 쿼리에서 별칭이 인식되지 않는 이유는 무엇입니까? (0) | 2023.10.06 |
---|---|
ajax를 사용하여 wordPress menu를 통해 div의 카테고리별 최신 게시물 로드 (0) | 2023.10.06 |
보이드로 변환하거나 그 반대로 변환하는 것은 무엇을 의미합니까? (0) | 2023.10.06 |
컴파일러 최적화 bitwise not operation (0) | 2023.10.06 |
자바스크립트에서 밀리초 단위로 (0) | 2023.10.06 |