一个简单的创建圆角图像的UIImage扩展实现

Swift中基于UIImage的实用扩展分类项目:实现颜色生成图片与常用图像处理功能 提供了精细控制各角落的能力。使用示例:适用于底部弹窗类卡片。场景推荐参数对话框顶部底部工具栏标签徽章, 半径≈高度一半气泡聊天框结合三角箭头路径合成结合缓存机制:return nil特性Core Image易用性高中执行速度快极快开发成本低高典型用途滤镜、色彩校正实时视频处理、AI推理。 阅读详情
在iOS开发中经常需要用到圆角图像。简单搜索一下就能找到很多创建圆角图像的实现代码。我在 Stack Overflow 上找到了一段代码,略微修改了一下,写了个简单的Category方法,可以用来创建圆角图像。代码如下:
 
/* UIImage+RoundedRect.h*/
#import <UIKit/UIKit.h>

@interface UIImage (RoundedCorner)
- (UIImage *)roundedCornerImageWithCornerRadius:(CGFloat)cornerRadius;
@end

/* UIImage+RoundedRect.m*/

#import "UIImage+RoundedCorner.h"

@implementation UIImage (RoundedCorner)

- (UIImage *)roundedCornerImageWithCornerRadius:(CGFloat)cornerRadius {
    CGFloat w = self.size.width;
    CGFloat h = self.size.height;
    CGFloat scale = [UIScreen mainScreen].scale;
    // 防止圆角半径小于0,或者大于宽/高中较小值的一半。
    if (cornerRadius < 0)
        cornerRadius = 0;
    else if (cornerRadius > MIN(w, h))
        cornerRadius = MIN(w, h) / 2.;

    UIImage *image = nil;
    CGRect imageFrame = CGRectMake(0., 0., w, h);
    UIGraphicsBeginImageContextWithOptions(self.size, NO, scale);
    [[UIBezierPath bezierPathWithRoundedRect:imageFrame cornerRadius:cornerRadius] addClip];
    [self drawInRect:imageFrame];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end

把这个Category添加到项目中之后,直接对UIImage对象调用- roundedCornerImageWithCornerRadius:方法即可。以上实现并非最高效,最佳的实现,但是有时候Quick and Dirty的方法已经足够好了,是吧。(天音:你就自我安慰吧。)

#import  < Foundation / Foundation.h >

typedef 
enum  {
    UIImageRoundedCornerTopLeft 
=   1 ,
    UIImageRoundedCornerTopRight 
=   1   <<   1 ,
    UIImageRoundedCornerBottomRight 
=   1   <<   2 ,
    UIImageRoundedCornerBottomLeft 
=   1   <<   3
} UIImageRoundedCorner;

@interface UIImage (Utility)

// + (void)addRoundedRectToPath(CGContextRef context, CGRect rect, float radius, UIImageRoundedCorner cornerMask);

-  (UIImage  * )roundedRectWith:( float )radius cornerMask:(UIImageRoundedCorner)cornerMask;

@end

 

 实现文件

 

#import  " UIImage+Utility.h "

// UIKit坐标系统原点在左上角,y方向向下的(坐标系A),但在Quartz中坐标系原点在左下角,y方向向上的(坐标系B)。图片绘制也是颠倒的。
static   void  addRoundedRectToPath(CGContextRef context, CGRect rect,  float  radius, UIImageRoundedCorner cornerMask)
{
    
// 原点在左下方,y方向向上。移动到线条2的起点。
    CGContextMoveToPoint(context, rect.origin.x, rect.origin.y  +  radius);
    
    
// 画出线条2, 目前画线的起始点已经移动到线条2的结束地方了。
    CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y  +  rect.size.height  -  radius);
    
    
// 如果左上角需要画圆角,画出一个弧线出来。
     if  (cornerMask  &  UIImageRoundedCornerTopLeft) {
        
        
// 已左上的正方形的右下脚为圆心,半径为radius, 180度到90度画一个弧线,
        CGContextAddArc(context, rect.origin.x  +  radius, rect.origin.y  +  rect.size.height  -  radius,
                        radius, M_PI, M_PI 
/   2 ,  1 );
    }
   
    
else  {
         
// 如果不需要画左上角的弧度。从线2终点,画到线3的终点,
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y  +  rect.size.height);
        
        
// 线3终点,画到线4的起点
        CGContextAddLineToPoint(context, rect.origin.x  +  radius, rect.origin.y  +  rect.size.height);
    }
    
    
// 画线4的起始,到线4的终点
    CGContextAddLineToPoint(context, rect.origin.x  +  rect.size.width  -  radius,
                            rect.origin.y 
+  rect.size.height);

    
// 画右上角
     if  (cornerMask  &  UIImageRoundedCornerTopRight) {
        CGContextAddArc(context, rect.origin.x 
+  rect.size.width  -  radius,
                        rect.origin.y 
+  rect.size.height  -  radius, radius, M_PI  /   2 ,  0.0f ,  1 );
    }
    
else  {
        CGContextAddLineToPoint(context, rect.origin.x 
+  rect.size.width, rect.origin.y  +  rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x 
+  rect.size.width, rect.origin.y  +  rect.size.height  -  radius);
    }

    CGContextAddLineToPoint(context, rect.origin.x 
+  rect.size.width, rect.origin.y  +  radius);

    
// 画右下角弧线
     if  (cornerMask  &  UIImageRoundedCornerBottomRight) {
        CGContextAddArc(context, rect.origin.x 
+  rect.size.width  -  radius, rect.origin.y  +  radius,
                        radius, 
0.0f ,  - M_PI  /   2 ,  1 );
    }
    
else  {
        CGContextAddLineToPoint(context, rect.origin.x 
+  rect.size.width, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x 
+  rect.size.width  -  radius, rect.origin.y);
    }

    CGContextAddLineToPoint(context, rect.origin.x 
+  radius, rect.origin.y);

    
// 画左下角弧线
     if  (cornerMask  &  UIImageRoundedCornerBottomLeft) {
        CGContextAddArc(context, rect.origin.x 
+  radius, rect.origin.y  +  radius, radius,
                        
- M_PI  /   2 , M_PI,  1 );
    }
    
else  {
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y 
+  radius);
    }

    CGContextClosePath(context);
}


@implementation UIImage (Utility)
-  (UIImage  * )roundedRectWith:( float )radius cornerMask:(UIImageRoundedCorner)cornerMask
{
    UIImageView 
* bkImageViewTmp  =  [[[UIImageView alloc] initWithImage:self] autorelease];

    
int  w  =  self.size.width;
    
int  h  =  self.size.height;

    CGColorSpaceRef colorSpace 
=  CGColorSpaceCreateDeviceRGB();
    CGContextRef context 
=  CGBitmapContextCreate(NULL, w, h,  8 ,  4   *  w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextBeginPath(context);
    addRoundedRectToPath(context,bkImageViewTmp.frame, radius, cornerMask);
    CGContextClosePath(context);
    CGContextClip(context);

    CGContextDrawImage(context, CGRectMake(
0 ,  0 , w, h), self.CGImage);

    CGImageRef imageMasked 
=  CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    UIImage    
* newImage  =  [UIImage imageWithCGImage:imageMasked];

    CGImageRelease(imageMasked);

    
return  newImage;
}

@end 

 

 实现方法如下:

-  (IBAction)showRectImage
{
    UIImage 
* rectImage  =  [UIImage imageNamed: @" test.jpg " ];
    self.imageView.image 
=  rectImage;
}

-  (IBAction)showRoundImage
{
    UIImage 
* rectImage  =  [UIImage imageNamed: @" test.jpg " ];
    UIImage 
* roundImage  =  [rectImage roundedRectWith: 100
                                          cornerMask:UIImageRoundedCornerBottomLeft
| UIImageRoundedCornerBottomRight | UIImageRoundedCornerTopLeft | UIImageRoundedCornerTopRight];
    self.imageView.image 
=  roundImage;
}


-  (IBAction)show2RoundImage
{
    UIImage 
* rectImage  =  [UIImage imageNamed: @" test.jpg " ];
    UIImage 
* round2Image  =  [rectImage roundedRectWith: 100
                                          cornerMask:UIImageRoundedCornerBottomLeft
| UIImageRoundedCornerBottomRight];
    self.imageView.image 
=  round2Image;

} 

 

对于四个角,用下面的角进行逻辑或的方法。

UIImageRoundedCornerTopRight
UIImageRoundedCornerTopLeft
UIImageRoundedCornerBottomRight

UIImageRoundedCornerBottomLeft 


+ (void)roundedImage:(UIImage *)image

          completion:(void (^)(UIImage *image))completion {

    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Begin a new image that will be the new image with the rounded corners

        // (here with the size of an UIImageView)

        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);

        CGRect rect = CGRectMake(0, 0, image.size.width,image.size.height);

        

        // Add a clip before drawing anything, in the shape of an rounded rect

        [[UIBezierPath bezierPathWithRoundedRect:rect

                                    cornerRadius:image.size.width/2] addClip];

        // Draw your image

        [image drawInRect:rect];

        

        // Get the image, here setting the UIImageView image

        UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();

        

        // Lets forget about that we were drawing

        UIGraphicsEndImageContext();

        dispatch_async( dispatch_get_main_queue(), ^{

            if (completion) {

                completion(roundedImage);

            }

        });

    });

}


NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty() Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to()输出(llama) (base) [root@localhost home]# nvidia-smi Unable to determine the device handle for GPU0000:09:00.0: Unknown Error。这是典型的“孤儿进程”,但它还是。(僵尸进程),占用 GPU 资源。如果进程仍然不消失,并且。,这意味着它的父进程是。 阅读详情

相关推荐

配置思科交换机冗余链路汇聚

本文对交换机端口汇聚配置进行说明

istrangeboy&begin zero的博客 6684

UIImage设置圆角

【代码】UIImage设置圆角。

qq_30252465的博客 575

ros1 Noetic下运行cartographer算法进行2d建图

最近的工作重点放在机器狗的二次开发上,项目的需求是要升级机器狗的slam算法和导航避障算法,slam拟采用激光与视觉融合算法,激光slam就使用最为流行和实用的cartoghper算法。在这过程中遇到好多坑,希望看到这篇博客的人能少走弯路吧。我用的仿真机器人是wpr_simiulation。首先复制一份demo_revo_lds.launch文件和revo_lds.lua文件,修改成下面的样子。my_test.lua文件,base_link就是机器人的坐标系。下载与安装的博客有很多,我推荐。

sun5739的博客 1547

通过绘制上下文的方式绘制图片圆角

//通过绘图的方式给图片设置圆角,而view的‘layer.cornerRadius’方法是离屏渲染,很消耗内存,所以可以通过下面的方法给图片设置圆角//为imageView 添加类别,给imageView的图片设置圆角-(void)imageWithCornerRadius:(CGFloat)radius { UIGraphicsBeginImageContextWithOpt

xia5879017的博客 436

差分分析.

差分分析是一种强大的密码攻击技术,通过研究明文差分与密文差分的关系来破解加密算法。本文系统介绍了差分分析的核心概念和方法: 基础差分分析:通过异或运算抵消密钥影响,利用差分分布表(DDT)寻找高概率差分特征,以FEAL-4为例展示了具体攻击过程。 高级差分技术:包括截断差分分析(关注部分特征)、不可能差分分析(排除概率为0的路径)和飞来去器分析(将算法分段处理)。 自动化搜索方法:介绍了松井算法和MILP(混合整数线性规划)方法,将差分路径搜索转化为数学优化问题。 这些方法展现了差分分析从基础理论到现代应用

weixin_61562383的博客 786

5G核心网Framed Routing功能解析:基于PFCP的帧路由机制与多终端互联实践

5G核心网Framed Routing功能解析:基于PFCP的帧路由机制与多终端互联实践

大家好,我是码农老gou,一名专注于编程技术的程序员。在这个博客中,我将与大家分享我在工作和学习中的经验、见解以及一些实用的技术干货。 1468

UIImage高性能圆角绘制,压缩,截屏,帧图片获取,修改原有image底色等各种功能持续更新

UIImage功能大全,持续收录

Deft_MKJing的博客 2048

飞书云文档API实战:从权限申请到自动化操作

本文详细介绍了飞书云文档API的实战应用,从权限申请到自动化操作。内容涵盖如何创建应用、获取关键API权限、理解并使用Tenant Access Token,并通过Python代码示例演示了读取和写入飞书表格数据的具体方法,旨在帮助开发者和业务人员实现文档数据处理的自动化,提升工作效率。

weixin_28318011的博客 1942

semantic-ui中图片的处理

1、基础样式   方式一:因为图片是使用img标签,所以直接将class加载img标签中即可。不过要注意的是,class中要指定是ui image。   方式二:使用一个span或者div将img标签包裹,然后ui image的class加载div或者span里面,img中只写一个src即可 <!-- 方式一 --> <img src="demo.png" class="ui image"> <!-- 方式二 --> <div clas...

weixin_51490695的博客 425

Aruco标签定位、测距、三维位置估算 opencv应用

摄像头要一开始对准aruco标签才开始运行。+ 相机标定文件(参考我的上篇文章)+ aruco标签6*6。

dgut_guangdian的博客 4222

【100%通过率】华为od统一考试B卷【贪吃蛇】Python 实现

贪吃蛇是一个经典游戏,蛇的身体由若干方格连接而成,身体随蛇头移动。蛇头触碰到食物时,蛇的长度会增加一格。蛇头和身体的任一方格或者游戏版图边界碰撞时,游戏结束。 下面让我们来完成贪吃蛇游戏的模拟。给定一个N*M的数组arr,代表N*M个方格组成的版图,贪吃蛇每次移动一个方格。若arr[i][j] == ‘H’,表示该方格为贪吃蛇的起始位置;若arr[i][j] == ‘F’,表示该方格为食物,若arr[i][j] == ‘E’,表示该方格为空格。贪吃蛇初始长度为1,初始移动方向为向左。

MISAYAONE的博客 1204

Swift UIImage扩展

import UIKit // MARK: 颜色转UIImage extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1.0, height: ...

chuangketong9015的博客 426

华为OD机考双机位C卷 - 完美走位 (Java & Python& JS & C/C++ & GO )

华为OD机考双机位C卷 - 完美走位(OD上机考试双机位C卷)。提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。

算法大师! 1125

给UIImage添加生成圆角图片的扩展API:

给UIImage添加生成圆角图片的扩展API: - (UIImage *)hyb_imageWithCornerRadius:(CGFloat)radius {   CGRect rect = (CGRect){0.f, 0.f, self.size};   UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.

小猴子 360

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

UIImage-Categories:iOS 图像处理利器

UIImage-Categories:iOS 图像处理利器 项目基础介绍与编程语言 UIImage-Categories 是一个基于Objective-C编写的强大工具集,专为解决在iOS平台上对UIImage对象进行裁剪和缩放时遇到的局限性而生。这个开源项目由Trevor Harmon最初创建,并由mbcharbonneau维护的一个分支,它针对性地解决了UIImage类在处理图片尺寸调整上的不...

gitblog_00711的博客 574

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

UIImage-Additions 项目推荐

UIImage-Additions 项目推荐 UIImage-Additions Adding utilities to UIImage! 项目地址: https://gitcode.com/gh_mirrors/ui/UIIma...

gitblog_00013的博客 406

推荐项目:UIImage+Additions - 图像处理的利器

推荐项目:UIImage+Additions - 图像处理的利器 项目介绍 如果你在iOS开发中经常遇到为不同颜色和形状调整图像的需求,那么UIImage+Additions将是你的得力助手。这是一个优雅的UIImage类别扩展,它提供了一系列方便的方法,可以让你轻松动态地生成彩色图像,添加圆角,调整阴影,甚至创建渐变色图像,而无需额外设计资源。 项目技术分析 UIImage+Additions基...

gitblog_00034的博客 327

UIImage的扩展方法——裁剪图片和等比列缩放图片-翻转-圆形等

首先创建一个UIImage类别,如下: @interface UIImage(UIImageScale)  -(UIImage*)getSubImage:(CGRect)rect;  -(UIImage*)scaleToSize:(CGSize)size;  @end     @implementation UIImage(UIImageScale)     //

备忘录-IOS知识等 5789

UIImage切圆角 - 优化

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34400525的博客 378

iOS--创建圆角图片的又一方法

UIImage+additions.h #import <UIKit/UIKit.h> @interface UIImage (additions) -(UIImage*)makeRoundCornersWithRadius:(const CGFloat)RADIUS; @end UIImage+additions.m #import "UIImage+additions.h" ...

weixin_33728268的博客 78

修改UIImage大小的正确姿势

本文是一篇英文的部分翻译,如有哪里不准确,欢迎指出。原文地址 更好的改变image大小的方式这一部分描述了改变UIImage对象大小的源代码合集。在功能上,它可能与你在各种网上论坛、博客能够找到的类似,但是它将他们的特性正和到一个独立的、可重用的包,并且提供了几个显著的提升。 * 额外的用于裁剪图片,生成缩略图的一些方法。 * 使用Objective-C的categories实现,易于服用。使用

a376552890的博客 1687

[Swift通天遁地]五、高级扩展-(8)ImageView(图像视图)的各种扩展方法

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/streng...

weixin_30376509的博客 195

ios 图片裁剪框架_ios UIImage 圆形图片剪切方案

@interfaceUIImage(Resize)//按形状切割图像-(UIImage*)cutImageWithRadius:(int)radius;@end//图片剪切-(UIImage*)cutImageWithRadius:(int)radius{UIGraphicsBeginImageContext(self.size);CGContextRefgc=UIGraphicsG...

weixin_29156401的博客 174

IOS 将图片转换为圆角图

UIImage+wiRoundedRectImage.h #import @interface UIImage (wiRoundedRectImage) + (id)createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(NSInteger)r; @end   UIImage+wiRou

Jason的专栏 697

UIImageView添加圆角

//UIImageView添加圆角 最直接的方法就是使用如下属性设置: imgView.layer.cornerRadius = 10;// 这一行代码是很消耗性能的 imgView.clipsToBounds = YES; **这是离屏渲染(off-screen-rendering),消耗性能的** //给UIImage添加生成圆角图片的扩展API:这是on-sc

chenjie1110的博客 636
上一篇: iOS应用性能调优的25个建议和技巧
下一篇: iOS 保持界面流畅的技巧
kingcodexl
博客等级 码龄12年 18粉丝 49原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值