gpt4 book ai didi

objective-c - 使用 UIImageView 屏蔽自定义形状

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:20 26 4
gpt4 key购买 nike

我想以编程方式在我的 UIImageView 上裁剪一个形状。我知道如何使用 QuartzCore 创建路径,但我不了解上下文。给我一个子类化 UIImageView 的例子。

那么我怎样才能使图像从这个开始:

Original Album Cover

对此:

Cropped Album Cover

我还需要 mask 是透明的

最佳答案

最简单的方法是

  • 为六边形创建一个 UIBezierPath
  • 从该路径创建一个CAShapeLayer;和
  • CAShapeLayer 作为 mask 添加到 ImageView 的 layer

因此,它可能看起来像:

CAShapeLayer *mask = [CAShapeLayer layer];
mask.path = [[self polygonPathWithRect:self.imageView.bounds lineWidth:0.0 sides:6] CGPath];
mask.strokeColor = [UIColor clearColor].CGColor;
mask.fillColor = [UIColor whiteColor].CGColor;
self.imageView.layer.mask = mask;

在哪里

/** Create UIBezierPath for regular polygon inside a CGRect
*
* @param square The CGRect of the square in which the path should be created.
* @param lineWidth The width of the stroke around the polygon. The polygon will be inset such that the stroke stays within the above square.
* @param sides How many sides to the polygon (e.g. 6=hexagon; 8=octagon, etc.).
*
* @return UIBezierPath of the resulting polygon path.
*/

- (UIBezierPath *)polygonPathWithRect:(CGRect)square
lineWidth:(CGFloat)lineWidth
sides:(NSInteger)sides
{
UIBezierPath *path = [UIBezierPath bezierPath];

CGFloat theta = 2.0 * M_PI / sides; // how much to turn at every corner
CGFloat squareWidth = MIN(square.size.width, square.size.height); // width of the square

// calculate the length of the sides of the polygon

CGFloat length = squareWidth - lineWidth;
if (sides % 4 != 0) { // if not dealing with polygon which will be square with all sides ...
length = length * cosf(theta / 2.0); // ... offset it inside a circle inside the square
}
CGFloat sideLength = length * tanf(theta / 2.0);

// start drawing at `point` in lower right corner

CGPoint point = CGPointMake(squareWidth / 2.0 + sideLength / 2.0, squareWidth - (squareWidth - length) / 2.0);
CGFloat angle = M_PI;
[path moveToPoint:point];

// draw the sides and rounded corners of the polygon

for (NSInteger side = 0; side < sides; side++) {
point = CGPointMake(point.x + sideLength * cosf(angle), point.y + sideLength * sinf(angle));
[path addLineToPoint:point];
angle += theta;
}

[path closePath];

return path;
}

我发布了另一个用 rounded corners 说明这个想法的答案,也是。

如果您想将此掩码的添加作为 UIImageView 子类的一部分来实现,我会把它留给您。但希望这能说明基本思想。

关于objective-c - 使用 UIImageView 屏蔽自定义形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com