gpt4 book ai didi

objective-c - 在 ImageView 中将数组绘制为图形

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:49 25 4
gpt4 key购买 nike

如何将数组绘制为 ImageView ?

我一直在 Playground 中测试它并且它有效,但如何在实际项目中将其绘制为 ImageView ?

let sineArraySize = 64

let frequency1 = 4.0
let phase1 = 0.0
let amplitude1 = 2.0
let sineWave = (0..<sineArraySize).map {
amplitude1 * sin(2.0 * M_PI / Double(sineArraySize) * Double($0) * frequency1 + phase1)
}


func plotArrayInPlayground<T>(arrayToPlot:Array<T>, title:String) {
for currentValue in arrayToPlot {
XCPCaptureValue(title, currentValue)
}
}


plotArrayInPlayground(sineWave, "Sine wave 1")

enter image description here

最佳答案

您可以这样做的一种方法:

// this function creates a plot of an array of doubles where it scales to the provided width and the x-axis is on half height
func plotArray(arr: [Double], width: Double, height: Double) -> NSImage {
if arr.isEmpty { return NSImage() }
let xAxisHeight = height / 2
let increment = width / Double(arr.count)
let image = NSImage(size: NSSize(width: width, height: height))

image.lockFocus()
// set background color
NSColor.whiteColor().set()

NSRectFill(NSRect(x: 0, y: 0, width: width, height: height))

let path = NSBezierPath()
// line width of plot
path.lineWidth = 5
path.moveToPoint(NSPoint(x: 0, y: arr[0] * increment + xAxisHeight))

var i = increment
for value in dropFirst(sineWave) {
path.lineToPoint(NSPoint(x: i, y: value * increment + xAxisHeight))
i += increment
}

// set plot color
NSColor.blueColor().set()
path.stroke()

image.unlockFocus()
return image
}

var imageView = NSImageView()
imageView.image = plotArray(sineWave, 500, 200)
// have fun

关于objective-c - 在 ImageView 中将数组绘制为图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com