0

I am creating a library icon class which receives an icon name, a flag 'isSF' (this flag will say whether the icon is SF Symbol or not) and the size of the icon. I need to resize both the icons as per the size value received. The issue I am facing here is , for SF Symbols, we can resize it using the .font(.system(size : value)) modifier but how to resize the image (custom icon) similarly.

Kindly help me. Thanks in advance

struct XIcon: View {
    var iconName: String
    var isSF: Bool? = true
    var size: CGFloat
    var body: some View {
        if isSF! {
            return AnyView( Image(systemName: "\(iconName)")
                .font(.system(size: size)))
        } else {
            return AnyView( Image(uiImage: UIImage(named: "\(iconName)")!).resizable())
        }
    }
}

Again, i know when we specify size, the vector alignment is carried out but for frame() it is not the case. For image scaling, scaleEffect() is there but i don't know how to scale the image equivalent to the size specified for SF Symbol

prebeesh
  • 51
  • 1
  • 9

1 Answers1

0

Here is possible solution. Tested with Xcode 11.4 / iOS 13.4

demo

Note: Borders are for better size visibility

struct XIcon: View {
    var iconName: String
    var isSF: Bool? = true
    var size: CGFloat

    var body: some View {
        var image: Image
        if isSF! {
            image = Image(systemName: "\(iconName)")
        } else {
            image = Image(uiImage: UIImage(named: "\(iconName)")!)
        }
        return image.resizable()
            .frame(width: size, height: size).aspectRatio(contentMode: .fill)
    }
}

struct TestXIcon: View {
    var body: some View {
        VStack {
            XIcon(iconName: "tv", size: 100)
                .border(Color.red)
            XIcon(iconName: "icon", isSF: false, size: 100)
                .border(Color.red)
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • The way you increase size is not a vector enlargement .. so the shape can be distorted. you can try the same with battery.25 icon. The resizing using .font(.system(size: value)) will give us the proper enlarged icon (it is done using vector enlargement ) but the solution you have given can distort the shape. Check the enlargement using both approach in battery.25 , you can find the exact change i meant. Thank you @Asperi – prebeesh Apr 24 '20 at 09:06
  • @prebeesh. The `.font(.system(size: value))`, ie. font size, is not about `Image` resizing, and not about *resizing* at all. No argue, it is your way, just in case. – Asperi Apr 24 '20 at 09:27
  • oh.. then is there any way to resize the icons without distortion? just as font size do? because when we frame it , the icons like battery is getting distorted. Do you have any solution to solve it? @Asperi – prebeesh Apr 24 '20 at 10:00