Swift-如何创建裁剪了形状的视图 [英] Swift - How to create a view with a shape cropped in it

查看:136
本文介绍了Swift-如何创建裁剪了形状的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用swift 1.2和xcode 6实现图像中显示的结果。

I'm trying to achieve the result shown in the image using swift 1.2 and xcode 6.

基本上我想创建一个带有剪切形状的视图才能看到下面的视图,从而为我的应用制作教程。
我知道如何创建圆形,但不知道如何在视图中将其切出。
我需要一个完整的例子来说明如何做。
预先感谢

Basically I want to create a view with a shape cut in it to be able to see the the view below to make a tutorial for my app. I know how to create a circular shape but i don't know how to cut it out in a view. I need a complete example on how to do it please. Thanks in advance

推荐答案

最简单的方法是创建一个png图像,该图像的外部周围部分透明白色,并且在周围有一个清晰的圆圈中间。然后,将2个图像视图彼此堆叠,并且将掩蔽图像堆叠在顶部,并设置其不透明图像。标记为false。

The easiest way to do this would be to create a png image with partly transparent white around the outside and a clear circle in the middle. Then stack 2 image views on top of each other, with the masking image on top, and set its "opaque" flag to false.

您也可以通过创建CAShapeLayer并将其设置为使用半透明的白色,然后安装一个形状为已切掉孔的正方形来实现此目的。形状。您将在图形视图层的顶部安装该形状层。

You could also do this by creating a CAShapeLayer and set it up to use a translucent white color, then install a shape that is the square with the hole cut out of it shape. You'd install that shape layer on top of your image view's layer.

最通用的方法是创建UIImageView的自定义子类,并使用init方法您的子类创建并安装shape层。昨天我刚刚创建了一个要点,它说明了如何创建UIImageView的自定义子类。这是链接: ImageViewWithGradient要点

The most general-purpose way to do that would be to create a custom subclass of UIImageView and have the init method of your subclass create and install the shape layer. I just created a gist yesterday that illustrated creating a custom subclass of UIImageView. Here is the link: ImageViewWithGradient gist

要点将创建一个渐变图层。相反,将其修改为创建形状图层将是一件简单的事情,如果您修改了layoutSubviews方法,则可以在调整图像视图的大小时使其适应视图和路径。

That gist creates a gradient layer. It would be a simple matter to adapt it to create a shape layer instead, and if you modified the layoutSubviews method you could make it adapt the view and path if the image view gets resized.

好吧,我采取了额外的步骤来创建一个创建裁剪图像视图的游乐场。您可以在 github上的ImageViewWithMask

Ok, I took the extra step of creating a playground that creates a cropping image view. You can find that at ImageViewWithMask on github

为我的游乐场生成的图像如下:

The resulting image for my playground looks like this:

这篇关于Swift-如何创建裁剪了形状的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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