使用Quartz in Cocoa OSX和iOS,你如何绘制线条和“连接”形状?

时间:2012-02-05 19:23:24

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

使用Objective C和Cocoa和Quartz的混合,是否有可能构建像Visio这样的东西?具体到:

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

2 个答案:

答案 0 :(得分:3)

你想要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提供的东西)。

答案 1 :(得分:0)

对于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()
    }   
}

你会得到:

enter image description here