簡體   English   中英

在UIImage周圍放置圓形框架的最簡單方法

[英]Easiest Way to Put a Circular Frame Around a UIImage

我正試圖為我正在構建的應用程序之一制作一個很酷的效果,並且寧願不使用drawRect函數。 你們能想到一個簡單的方法在UIImage周圍放一個漂亮的圓形邊框嗎? 它看起來應該像圓形相框。

這是我到目前為止所使用的:

CGFloat radius = self.layer.bounds.size.width / 2;

    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.frame = self.layer.bounds;
    [mask setFillColor:[[UIColor whiteColor] CGColor]];

    CGFloat width = self.layer.bounds.size.width;
    CGFloat height = self.layer.bounds.size.height;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, width, 0);
    CGPathAddLineToPoint(path, NULL, width, height - radius);
    CGPathAddCurveToPoint(path, NULL, width, height, width - radius, height, width - radius, height);
    CGPathAddLineToPoint(path, NULL, 0, height);
    CGPathAddLineToPoint(path, NULL, 0, radius);
    CGPathAddCurveToPoint(path, NULL, 0, 0, radius, 0, radius, 0);
    CGPathCloseSubpath(path);
    [mask setPath:path];
    CGPathRelease(path);

    self.layer.mask = mask; 

    [self setNeedsDisplay];

我的UIImage封裝在一個UIView中(self是一個UIView)。 我期待它繞着我的UIView畫一個圓圈。

可能最好的方法是使用QuartzCore。

基本上你需要包含QuartzCore框架,然后創建一個UIView來放入你的圖像,然后圍繞它的角落並將它的clipsToBounds屬性設置為YES。

例:

#include <QuartzCore/QuartzCore.h>

//More code stuff

UIView *newView = [[UIView alloc] initWithFrame:frame];
newView.clipsToBounds = YES;
newView.layer.cornerRadius = 10;
[newView addSubview:imageView];

您可以在UIImageView的圖層上使用蒙版,或者只將角半徑設置為高度的一半。 無論哪種情況,一定要#import <QuartzCore/QuartzCore.h>

myImageView.layer.cornerRadius = myImageView.bounds.size.width / 2;

用於制作兩個圓角的示例蒙版(更改為使其成為圓形):

+ (void) applyTwoCornerMask: (CALayer *) layer withRadius: (CGFloat) radius {
    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.frame = layer.bounds;
    [mask setFillColor:[[UIColor blackColor] CGColor]];

    CGFloat width = layer.bounds.size.width;
    CGFloat height = layer.bounds.size.height;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, width, 0);
    CGPathAddLineToPoint(path, NULL, width, height - radius);
    CGPathAddCurveToPoint(path, NULL, width, height, width - radius, height, width - radius, height);
    CGPathAddLineToPoint(path, NULL, 0, height);
    CGPathAddLineToPoint(path, NULL, 0, radius);
    CGPathAddCurveToPoint(path, NULL, 0, 0, radius, 0, radius, 0);
    CGPathCloseSubpath(path);
    [mask setPath:path];
    CGPathRelease(path);

    layer.mask = mask;  
}

如何使用以下方法:使用位於原始頂部的第二個UIImageView,該原始圖像包含您想要的圖像。 第二個UIImageView具有可伸縮版本的相框圖像,因此如果原始圖像改變大小,您的相框可能會發生變化。

不容易重復使用,但這很簡單。

您可以使用UIImage的stretchableImageWithLeftCapWidth方法來創建圖片框架圖像的可伸縮版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM