[英]Why is are the images being cut off?
我的“瓷磚”中的圖像在兩側被切斷。 我正在嘗試為每個顯示圖像、名稱和副標題的“產品”創建一個磁貼。 除了圖像之外,現在一切正常。 這是因為圖塊上的圖像在兩側被切掉了。
ContentView 的視圖如下所示:
ScrollView(.vertical, showsIndicators: false, content: {
Spacer()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(),spacing: 15), count: 2),spacing: 10){
ForEach(HomeModel.filteredProduct){product in
// Product View...
ProductView(productData: product)
.background(.white)
.clipShape(RoundedRectangle(cornerRadius: 15, style: .continuous))
.shadow(color: .black.opacity(0.4), radius: 3, x: 1, y: 1)
.onTapGesture {
withAnimation(.easeIn){
selectedProduct = charity
show.toggle()
}
}
}
}
Spacer()
.padding()
.padding(.top,10)
})
.padding(.top, 20)
ProductView代碼如下:
var body: some View {
VStack(alignment: .center, spacing: 0) {
WebImage(url: URL(string: productData.product_image))
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 160, height: 225)
.cornerRadius(15)
.clipped()
.padding(5)
Text(productData.product_name)
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.black)
.padding()
Text(productData.product_type)
.font(.caption)
.foregroundColor(.gray)
.lineLimit(2)
.padding()
}
}
這是一張圖片,顯示了“瓷磚正在切斷”的含義:
正如您在照片中看到的那樣,圖像並未全部包含在內,因為它不適合磁貼。 這需要調整大小。
這里的第一個問題是需要設置為填充的.contentMode
修飾符。 如果您的圖像寬度大於高度,但您將框架設置為不同的縱橫比,您將在圖像上方和下方看到一個空白區域。
但也有其他問題。 您需要在設置框架后使用.clipped()
修飾符裁剪圖像,否則它會溢出框架。 為什么所有這些ZStacks
? 我看不出添加只有一個孩子的ZStack
的任何目的。
由於您的代碼不可重現,我必須添加或刪除一些內容才能使其正常工作。 所以你需要在你的代碼中采用它。
struct ContentView: View{
@State private var products: [ProductData] = [ProductData(product_name: "test", product_details: "test"), ProductData(product_name: "test2", product_details: "test2"), ProductData(product_name: "test3", product_details: "test3")]
@State private var show = false
@State private var selectedProduct: ProductData?
var body: some View{
ScrollView(.vertical, showsIndicators: false, content: {
Spacer()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(),spacing: 15), count: 2),spacing: 10){
ForEach(products){product in
// Product View...
ProductView(productData: product)
.background(.white)
.clipShape(RoundedRectangle(cornerRadius: 15, style: .continuous))
.shadow(color: .black.opacity(0.4), radius: 3, x: 1, y: 1)
.onTapGesture {
withAnimation(.easeIn){
selectedProduct = product
show.toggle()
}
}
}
}
Spacer()
.padding()
.padding(.top,10)
})
.padding(.top, 20)
}
}
struct ProductData: Identifiable{
var id = UUID()
var product_name: String
var product_details: String
}
struct ProductView: View{
var productData: ProductData
var body: some View{
VStack(alignment: .center, spacing: 0) {
Image("test")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 160, height: 225)
.cornerRadius(15)
.clipped()
.padding(5)
Text(productData.product_name)
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.black)
.padding()
Text(productData.product_details)
.font(.caption)
.foregroundColor(.gray)
.lineLimit(2)
.padding()
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.