Image
显示图像的view
定义
@frozen struct Image
简介
Image是个后绑定的控件,系统只在需要它的时候才会给它赋予实际的数值。
基础使用
1、 显示图片
import SwiftUI
struct ContentView: View {
var body: some View {
Image("1")
}
}
效果
image.png2、 自动适应大小
例子1的图片没有完全显示全,我们可以用Image的resizable()来让图片自动适应
struct ContentView: View {
var body: some View {
Image("1")
.resizable()
}
}
效果
image.png
3. 保持原始比例
但是,这也可能导致图像的原始纵横比失真,因为它将在所有尺寸上拉伸所需的任何量以使其填充空间。
struct ContentView: View {
var body: some View {
Image("1")
.resizable()
.aspectRatio(contentMode: .fit)
}
}
image.png
4. 点击放大
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image("1")
.resizable()
.aspectRatio(contentMode: .fit)
.scaleEffect(scale)
.gesture(
TapGesture()
.onEnded { _ in
self.scale += 0.1
print("\(self.scale)")
}
)
}
}
效果
Jietu20200101-220135.gif
5、手势放大
struct ContentView: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Image("1")
.resizable()
.aspectRatio(contentMode: .fit)
.scaleEffect(scale)
.gesture(MagnificationGesture()
.onChanged { value in
self.scale = value.magnitude
}
)
}
}
Jietu20200101-220918.gif
6、随手势移动
@GestureState private var dragOffset = CGSize.zero
@State private var position = CGSize.zero
var body: some View {
Image("1")
.font(.system(size: 100))
.offset(x: position.width + dragOffset.width, y: position.height + dragOffset.height)
.animation(.easeInOut)
.foregroundColor(.green)
.gesture(
DragGesture()
.updating($dragOffset, body: { (value, state, transaction) in
state = value.translation
})
.onEnded({ (value) in
self.position.height += value.translation.height
self.position.width += value.translation.width
})
)
}
6、完整拖拽缩放三个手势都支持
import SwiftUI
struct ContentView: View {
@GestureState private var dragOffset = CGSize.zero
@State private var position = CGSize.zero
@State private var scale: CGFloat = 1.0
var body: some View {
Image("1")
.resizable()
.aspectRatio(contentMode: .fit)
.offset(x: position.width + dragOffset.width, y: position.height + dragOffset.height)
.animation(.easeInOut)
.scaleEffect(scale)
// 缩放
.gesture(MagnificationGesture()
.onChanged { value in
self.scale = value.magnitude
}
)
// 拖拽
.gesture(
DragGesture()
.updating($dragOffset, body: { (value, state, transaction) in
state = value.translation
})
.onEnded({ (value) in
self.position.height += value.translation.height
self.position.width += value.translation.width
})
)
//点击放大
.gesture(
TapGesture()
.onEnded { _ in
self.scale += 0.1
print("\(self.scale)")
}
)
}
}
效果
a.gif
网友评论