swift ui 图片缩放

312 阅读1分钟

学习笔记:

最近在学习iOS的swift ui 里面的图片缩放 所以做一个笔记

效果图:

  • 未缩放

image.png

  • 放大

image.png

具体实现:

  • 添加一个image

       Image("home").resizable()
                .aspectRatio(contentMode:self.zoomed ? .fill: .fit)
                .navigationBarTitle(Text("徐老板"))
                .onTapGesture {
                    withAnimation{
                        self.zoomed.toggle()
                    }
            }

定义一个布尔值变量 :

    @State private var zoomed:Bool=false
  • 点击手势处理缩放

   .onTapGesture {
                    withAnimation{
                        self.zoomed.toggle()
                    }
            }
  • 完整代码

//
//  ContentView.swift
//  imagezoom
//
//  Created by xuqing on 2021/11/22.
// 图片缩放
//

import SwiftUI

struct ContentView: View {
    
    @State private var zoomed:Bool=false
    var body: some View {
        ZStack(alignment: self.zoomed ? .top :.topTrailing) {
            Image("home").resizable()
                .aspectRatio(contentMode:self.zoomed ? .fill: .fit)
                .navigationBarTitle(Text("徐老板"))
                .onTapGesture {
                    withAnimation{
                        self.zoomed.toggle()
                    }
            }
            
            Image("xiaoma")
                .resizable()
                .frame(width: 50, height: 50, alignment: .center)
                .padding(.all,10)
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

最后总结:

学习笔记记录