如何在 SwiftUI 中动态调整图像大小以实现可访问性? [英] How to dynamically size an image in SwiftUI for accessibility?

查看:50
本文介绍了如何在 SwiftUI 中动态调整图像大小以实现可访问性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片,我对尺寸进行了硬编码,但意识到它不会针对较大尺寸的类别进行缩放.如何设置首选尺寸并让它自动缩放到不同尺寸?

I have an image that I'm hard coding the size, but realized it's not scaling for larger size categories. How can I set a preferred size and let it scale up to different sizes automatically?

这是我的代码的样子:

HStack(alignment: .top, spacing: 4) {
    Text("Some text")
    Button(action: { showAlert = true }) {
        Image(systemName: "questionmark.circle.fill")
            .resizable()
            .frame(width: 12, height: 12)
            .foregroundColor(.secondary)
    }
}

我还有其他不使用 SF 符号的情况:

I also have other scenario where it's not using a SF Symbol:

Button(action: action) {
    Label(
        title: {
            Text(title)
                .foregroundColor(Color(.label))
        },
        icon: {
            Image("twitter")
                .resizable()
                .frame(width: 24, height: 24)
        }
    )
}

这是在不同尺寸的预览中的外观,但在较大的比例下图像很小.我该如何处理以实现可访问性?

This is how it looks in preview in different sizes, but the images are tiny in the larger scales. How do I handle this to achieve accessibility?

推荐答案

SwiftUI 2.0 为此提供了 ScaleMetric.

SwiftUI 2.0 provides ScaleMetric for this purpose.

这是解决方案的演示.使用 Xcode 12.1/iOS 14.1 测试

Here is a demo of solution. Tested with Xcode 12.1 / iOS 14.1

普通文本:

最大文本:

struct TestScaledImage: View {
    @ScaledMetric var scale: CGFloat = 1     // << here !!
    var body: some View {
        HStack(alignment: .top, spacing: 4) {
            Text("Some text")
            Button(action: {  }) {
                Image(systemName: "questionmark.circle.fill")
                    .resizable()
                    .frame(width: 12 * scale, height: 12 * scale)  // << here !!
                    .foregroundColor(.secondary)
            }
        }
    }
}

这篇关于如何在 SwiftUI 中动态调整图像大小以实现可访问性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆