2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Swift UI]正方形のカメラ画面を作成する方法

Last updated at Posted at 2023-01-16

結論から書くとカメラサイズを指定してあげればOKです

IMG_81FB47237FC0-1.jpeg

画面が横になってるのは横画面のアプリを作ってるからです(コメントアウトして外してあります)

まずはinfo.plistでこちらを追加

カメラの権限です

Privacy - Camera Usage Description

そしてコードはこちら(コピペでok)

import SwiftUI
import AVFoundation

struct ContentView: View {
    var body: some View {
  
        VStack{
            CameraView()
        }
        .frame(width: 300, height: 300)
        .background(Color.orange)
    }
}

struct CameraView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView { BaseCameraView() }
    func updateUIView(_ uiView: UIViewType, context: Context) {}
}

class BaseCameraView: UIView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        _ = initCaptureSession
        (layer.sublayers?.first as? AVCaptureVideoPreviewLayer)?.frame = frame

    }

    lazy var initCaptureSession: Void = {
        guard let device = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera],
            mediaType: .video,
            position: .unspecified)
            .devices.first(where: { $0.position == .front }),
        let input = try? AVCaptureDeviceInput(device: device) else { return }
        let session = AVCaptureSession()
        session.addInput(input)
        session.startRunning()
        let previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.videoGravity = .resizeAspectFill //←これが必要
//        previewLayer.connection?.videoOrientation = .landscapeRight
        layer.insertSublayer(previewLayer, at: 100)


    }()
}

カメラのサイズを正方形にする必要がありどうやってもできなくて詰まってたんですが、なんとか記事を見つけて修正したらできました

swift ui カメラ 正方形でググってもそれっぽい記事が出てこなくてイライラしたのでそういう思いをしてほしくないなと思い忘備録を残します

どなたかの参考になれば幸いです

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?