You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在macOS Swift Playgrounds中能否绘制线条、圆形等简单像素图形?

Swift Playgrounds 简单像素绘图解决方案

一、可用框架与组件说明

  • iOS/iPadOS 版 Playgrounds 完全支持 UIKit 和 CoreGraphics,UIView 可直接用于自定义绘图;macOS 版则支持 AppKit 与 NSView,核心绘图能力依赖原生框架,没有专属的替代组件。
  • 你提到的精灵、GL 相关示例是 Playgrounds 针对游戏开发的预设场景,基础像素绘图依然可以通过原生框架实现。

二、极简像素绘图代码示例(iOS)

下面是一个可直接在 iOS Playgrounds 运行的像素绘制代码,通过自定义 UIView 操作像素缓冲区:

import UIKit
import PlaygroundSupport

class PixelCanvasView: UIView {
    override func draw(_ rect: CGRect) {
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        
        // 定义画布尺寸(100x100像素)
        let canvasWidth = 100
        let canvasHeight = 100
        let bytesPerPixel = 4 // RGBA各占1字节
        let totalBytes = canvasWidth * canvasHeight * bytesPerPixel
        
        // 初始化像素数据(默认全透明黑色)
        var pixels = [UInt8](repeating: 0, count: totalBytes)
        
        // 绘制一个红色像素在中心
        let centerX = canvasWidth / 2
        let centerY = canvasHeight / 2
        let pixelOffset = (centerY * canvasWidth + centerX) * bytesPerPixel
        pixels[pixelOffset] = 255     // R
        pixels[pixelOffset + 1] = 0   // G
        pixels[pixelOffset + 2] = 0   // B
        pixels[pixelOffset + 3] = 255 // A
        
        // 将像素数据转换为CGImage并绘制
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
        guard let cgImage = CGImage(
            width: canvasWidth,
            height: canvasHeight,
            bitsPerComponent: 8,
            bitsPerPixel: 32,
            bytesPerRow: canvasWidth * bytesPerPixel,
            space: colorSpace,
            bitmapInfo: CGBitmapInfo(rawValue: bitmapInfo),
            provider: CGDataProvider(data: Data(pixels) as CFData)!,
            decode: nil,
            shouldInterpolate: false,
            intent: .defaultIntent
        ) else { return }
        
        ctx.draw(cgImage, in: bounds)
    }
}

// 在Playgrounds中展示画布
let canvas = PixelCanvasView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
canvas.backgroundColor = .white
PlaygroundPage.current.liveView = canvas

三、常见问题排查

  • 之前的代码被拒绝,大概率是因为缺少 PlaygroundSupport 框架导入(必须用它来展示自定义视图),或者使用了 Playgrounds 沙箱限制的 API(比如文件操作);
  • 如果是 macOS 版本,只需将 UIView 替换为 NSView,UIGraphicsGetCurrentContext() 替换为 NSGraphicsContext.current?.cgContext 即可适配。

内容的提问来源于stack exchange,提问作者hippietrail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:10:18