Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CoreGraphicsでドット絵を描こう/iOSDC22

noppefoxwolf
September 11, 2022

 CoreGraphicsでドット絵を描こう/iOSDC22

noppefoxwolf

September 11, 2022
Tweet

More Decks by noppefoxwolf

Other Decks in Programming

Transcript

  1. 3

  2. 4

  3. 6

  4. 9

  5. υοτֆΛදࣔ͢Δ // Use nearest magnificationFilter imageView.contentMode = .scaleAspectFit imageView.layer.magnificationFilter =

    .nearest imageView.image = UIImage(named: "watch") // SwiftUI Image(...).interpolation(.none) -ɹը૾ࣗମͷϦαΠζ͸ॏ͘ϝϞϦΛ࿘ අ͢ΔͷͰNG 15
  6. 17

  7. 18

  8. υοτֆΤσΟλͷϫʔΫϑ ϩʔ let imageView = UIImageView() let context = CGContext()

    func setup() { imageView.onTap = { point in // 1 context.fill(point) // 2 let image = context.makeImage() // 3 imageView.image = image // 4 } } 19
  9. άϨʔεέʔϧͷCGContextͷॳظԽ // άϨʔεέʔϧઐ༻ͷCGContextΛੜ੒ let context = CGContext( data: nil, width:

    16, height: 16, bitsPerComponent: 8, bytesPerRow: 1 * 16, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue ) 20
  10. bitsPerComponent • 1,2,4,8 bit͔Β1৭ͷ֊ௐΛࢦఆ͢Δ • 4bit = 16֊ௐ • 8bit

    = 256֊ௐ • RGBͳͲɺෳ਺ͷίϯϙʔωϯτͰ৭Λද͢͜ͱ΋͋Γ·͢ 21
  11. bitmapInfo • ΞϧϑΝνϟϯωϧͷ৔ॴ | όΠτΦʔμʔ | ϑΥʔϚοτɹͷ ϏοτϚεΫ ྫ •

    CGImageAlphaInfo.noneSkipLast.rawValue | CGImageByteOrderInfo.order32LiCle.rawValue | CGImagePixelFormatInfo.packed.rawValue • CGImageAlphaInfo.none.rawValue 24
  12. 25

  13. contextͷը૾Λඳը͢Δ let cgImage: CGImage = context.makeImage()! let uiImage: UIImage =

    UIImage( cgImage: cgImage, scale: 1, orientation: .downMirrored // UIImageͷ࠲ඪܥʹม׵ ) // UIKit imageView.image = uiImage // SwiftUI Image(uiImage: uiImage) 26
  14. ৭ͷృΓͭͿ͠ let color = CGColor(gray: 0, alpha: 1) context.setFillColor(color) let

    path = CGPath( rect: CGRect(origin: point, size: CGSize(width: 1, height: 1)) ) context.addPath(path) // Pathͷ௥Ճ context.fillPath() 27
  15. 29

  16. 30

  17. 31

  18. CGContextʹࣗ࡞ؔ਺Λੜ΍͢ extension CGContext { func fillEllipseLine(in rect: CGRect) { //

    ృΓͭͿ͢ύεΛ࡞Δ let path = makeEllipsePath(in: rect) // ύεΛ௥Ճ addPath(path) // ௥Ճͨ͠ύεΛృΓͭͿ͢ fillPath() } } 32
  19. ϝϞϦϨΠΞ΢τΛ֬ೝ͢Δ 2x2ͷCGContextΛ ৭ ɹ৭ʢHexʣɹ Ґஔ 17.0 / 255.0 0x11 ɹࠨԼ

    34.0 / 255.0 0x22 ɹӈԼ 51.0 / 255.0 0x33 ɹࠨ্ 68.0 / 255.0 0x44 ɹӈ্ ͷάϨʔ஋̐৭Ͱண৭ 37
  20. CGContextͷdata͔Β৭ΛऔΓग़͢ struct GrayColor { let gray: UInt8 } // ϙΠϯλ͔Βઌ಄8bitΛGrayColorͱͯ͠औΓग़͢

    let color = data.load(as: GrayColor.self) // 100ϐΫηϧ໨ͷ৭ΛऔΓग़͢ let color = data.load( fromByteOffset: MemoryLayout<GrayColor>.size * 100, as: GrayColor.self ) 41
  21. ΠϯσοΫεΧϥʔϑΟϧλͷ࣮૷ float4 lookupTable(sampler src, sampler lut) { float2 pos =

    src.coord(); float4 pixelColor = src.sample(pos); int index = pixelColor.r * 255; int x = index % int(lut.size().x); int y = index / int(lut.size().y); float2 lutPos = float2(x, y); float4 lutColor = lut.sample(lutPos); return lutColor; } • noppefoxwolf/PixelArtKit 47