【问题标题】:With Quartz in Cocoa OSX and iOS, how do you draw lines and "connect" shapes?使用 Cocoa OSX 和 iOS 中的 Quartz,您如何绘制线条和“连接”形状?
【发布时间】:2012-02-05 19:23:24
【问题描述】:

使用 Objective C 和一些 Cocoa 和 Quartz 的组合,是否可以构建类似 Visio 的东西?具体到:

  1. 从一个对象到另一个对象画一条线,
  2. 让它连接到第二个对象并“锁定”到第二个对象,在该线的任一端都有一个彩色方块指向箭头,并且
  3. 如果拖动对象,则保持线连接。

【问题讨论】:

    标签: cocoa core-graphics draw shape quartz-2d


    【解决方案1】:

    您希望在 OSX 上使用 NSBezierPath,在 iOS 上使用 UIBezierPath。以 OSX 为例,在 NSView 中从 A 到 B(其中 A 和 B 是 NSPoints)画一条线:

    - (void)drawRect:(NSRect)dirtyRect {
      NSBezierPath *path = [NSBezierPath bezierPath];
      [path moveToPoint:A];
      [path lineToPoint:B];
      [path stroke];
    }
    

    如果你想绘制一个由 NSRect r 表示的盒子,你会这样做:

    NSBezierPath *path = [NSBezierPath bezierPathWithRect:r];
    [path stroke];
    

    等等。你可以做很多事情。

    就跟踪连接而言,这是您必须自己处理的事情(即不是 OSX/iOS 提供的事情)。

    【讨论】:

    • 谢谢,刚刚试了一下,你给了我一些想法。不错。
    【解决方案2】:

    我在 OSX && swift 4.x 上的两分钱(在 Xcode 9.1 上测试)

    //  CustomView.swift
    //  cocoaCustomDraw
    //
    //  Created by ing.conti on 1/28/18.
    //  Copyright © 2018 ing.conti. All rights reserved.
    //
    
    import Cocoa
    
    class CustomView: NSView {
    
        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
    
            // Drawing code here.
    
            // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Introduction/Introduction.html
    
            guard let aContext = NSGraphicsContext.current else{
                return
            }
    
            // eventually..
            aContext.saveGraphicsState()
    
            // Set the drawing attributes
    
            // Draw the object
            NSColor.blue.set()
            NSColor.yellow.setFill()
    
            // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html
    
            let aPath = NSBezierPath()
            aPath.move(to: NSPoint(x: 0, y: 0))
            aPath.line(to: NSPoint(x: 100, y: 100))
    
            aPath.curve(to: NSPoint(x:180, y: 210),
            controlPoint1: NSPoint(x: 60, y: 20),
            controlPoint2: NSPoint(x: 280, y: 100))
    
            //aPath.appendRect( NSRect(x: 2.0, y: 16.0, width:  8.0,  height: 5.0))
    
            aPath.close()
    
            aPath.fill()
            aPath.stroke()
    
    
            // eventually..
            aContext.restoreGraphicsState()
        }   
    }
    

    你会得到:

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多