SwiftUI中的常用图形(Shapes)

概述

SwiftUI中,常用的图形(Shape)主要有:
Circle:圆形
Ellipse:椭圆形
Capsule:胶囊形
Rectangle:矩形
RoundedRectangle:圆角矩形
上面的这些图形都继承了Shape协议,除了上面给出的图形,也可以通过path方法自定义图形。

func path(in rect: CGRect) -> Path

上述图形中,他们不像Text或者Button这类组件是根据自身内容自适应frame的,而是默认填充其父视图的大小,除非指定frame。

修饰器(modifier)

通过修饰器,可以设置图形的各种属性,包括颜色,边框,大小,等等。

1. 填充颜色
填充颜色即设置图形的颜色,可以通过下面两个方法设置:
.fill()
.foregroundColor()
两个方法中可以直接颜色参数,比如:
.fill(Color.red)
.foregroundColor(.blue)

除了设置具体的颜色,还可以设置渐变色,比如:
.fill(LinearGradient(colors: [Color.red, Color.blue], startPoint: .top, endPoint: .bottom))
.foregroundColor(LinearGradient(colors: [Color.red, Color.blue], startPoint: .top, endPoint: .bottom))

.fill()方法中还可以添加一个style参数,比如:.fill(Color.red, style: FillStyle(eoFill: true, antialiased: false))
FillStyle结构体中的isEOFilledisAntialiased是两个属性,用于控制填充的行为和渲染效果。

在这里插入图片描述

2. 边框
设置边框最直接的方法:.stroke(),如果不设置任何参数,则取默认的颜色,黑色或者白色。
通常可以设置的参数如下:
.stroke(Color.red)
.stroke(Color.blue, lineWidth: 10.0)
.stroke(Color.blue, style: StrokeStyle(lineWidth: 10, lineCap: .round, dash: [40]))
在这里插入图片描述
通过StrokeStyle,我们可以设置出一个虚线边框。

3. 裁剪
通过.trim方法可以对图形进行裁剪。比如:
.trim(from: 0.5, to: 1)
.trim(from: 0, to: 0.5)
.trim(from: 0.25, to: 0.75)
.trim(from: 0.3, to: 1.0)

参数:
from:绘制图形时的起始部分。
to:绘制图形时的结束部分。
通过使用trim方法,我们可以在SwiftUI中轻松地裁剪形状的一部分,实现更加灵活和多样化的视觉效果。
在这里插入图片描述

写在最后

上面是用圆形做了一些基本修饰器的举例,除了这些,个别图形在创建的时候也有自己的独有的属性,比如创建RoundedRectangle的时候,需要给定cornerRadius。还有CapsuleRoundedRectangle创建的时候也可以设置style属性。
很多的时候这些形状可以作为文字或者按钮的背景存在,以实现更好的效果。

var body: some View {
    VStack(spacing: 20) {
      Circle()
        .fill(Color.red)
      Ellipse()
        .fill(LinearGradient(colors: [Color.red, Color.blue], startPoint: .top, endPoint: .bottom))
      Capsule(style: .circular)
        .foregroundColor(.blue)
      Rectangle()
        .stroke(Color.blue, lineWidth: 10.0)
      RoundedRectangle(cornerRadius: 25.0, style: RoundedCornerStyle.continuous)
        .stroke(Color.blue, style: StrokeStyle(lineWidth: 20, lineCap: .round, dash: [40]))
    }
    .padding()
  }

在这里插入图片描述

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值