iOS SwiftUI 自己动手做个图片与照片选择器Picker

iOS SwiftUI 自己动手做个图片与照片选择器Picker

看看效果

iOS SwiftUI 自己动手做个图片与照片选择器Picker_第1张图片

用到工具

  • enum 枚举类型
  • @Binding
  • 视图的.onTapGesture修饰器
  • 图片剪裁
  • 图片边框

实现步骤

1、 用enum类型管理颜色

enum PickedColor: CaseIterable {
  case black, blue, green, orange, red, yellow
  
  var color: Color {
    return Color(uiColor)
  }
  
  var uiColor: UIColor {
    switch self {
    case .black:
      return UIColor(named: "Black")!
    case .blue:
      return UIColor(named: "Blue")!
    case .green:
      return UIColor(named: "Green")!
    case .orange:
      return UIColor(named: "Orange")!
    case .red:
      return UIColor(named: "Red")!
    case .yellow:
      return UIColor(named: "Yellow")!
    }
  }
}

2、颜色选择效果

struct ColorPicker: View {
  @Binding var pickedColor: PickedColor
  
  let diameter: CGFloat = 40
  
  var body: some View {
    HStack {
      ForEach(PickedColor.allCases, id: \.self) { pickedColor in
        ZStack {
          Circle()
            .foregroundColor(pickedColor.color)
            .frame(width: self.diameter,
                   height: self.diameter)
            .onTapGesture {
              self.pickedColor = pickedColor
              print  ("\(PickedColor.allCases.firstIndex(of: pickedColor)!)")
          }
          Circle()
            .foregroundColor(.white)
            .frame(width: self.pickedColor == pickedColor ? self.diameter * 0.25 : 0)
        }
      }
    }
    .frame(height: diameter * 3)
  }
}

3、照片选择效果

struct ColorPickerView: View {
  @State var pickedColor: PickedColor = .red
  var body: some View {
    VStack {
        Image("\(PickedColor.allCases.firstIndex(of: pickedColor)!+1)")
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width:250,height: 250)
        .clipShape( Circle())
        .overlay(Circle()
            .stroke(lineWidth:8)
            .foregroundColor(pickedColor.color)
        )
        
      ColorPicker(pickedColor: $pickedColor)
    }
  }
}

如果需要项目完整源码,可以加我QQ。

QQ:3365059189
SwiftUI技术交流QQ群:518696470

https://www.jianshu.com/c/7b3...

你可能感兴趣的:(ios,swift)