You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求教:如何在Objective-C中创建重复勾选框(checks)图像?

在Objective-C中创建重复勾选框样式图像的可行方案和建议

当然有可行的方案!在Objective-C里实现这种重复的勾选框图案,我常用下面几种思路,给你详细拆解:

方案1:Core Graphics手动绘制重复图案

这是最灵活的方式,你可以完全自定义勾选框的样式(比如方框粗细、勾选标记形状、颜色等),然后生成重复平铺的图像。

实现代码示例

- (UIImage *)createRepeatingCheckmarkImage {
    // 单个勾选框瓦片的尺寸,可根据需求调整
    CGFloat tileEdgeLength = 24.0f;
    CGSize tileSize = CGSizeMake(tileEdgeLength, tileEdgeLength);
    
    // 开启绘图上下文,适配Retina屏幕
    UIGraphicsBeginImageContextWithOptions(tileSize, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 设置样式参数:边框颜色、线宽
    UIColor *borderColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    [borderColor setStroke];
    CGContextSetLineWidth(context, 1.5f);
    
    // 绘制勾选框的外框
    CGRect boxRect = CGRectInset(CGRectMake(0, 0, tileEdgeLength, tileEdgeLength), 3.0f, 3.0f);
    CGContextStrokeRect(context, boxRect);
    
    // 绘制内部的勾选标记(如果需要未勾选的样式,直接注释这段即可)
    UIBezierPath *checkMarkPath = [UIBezierPath bezierPath];
    [checkMarkPath moveToPoint:CGPointMake(5.0f, tileEdgeLength/2)];
    [checkMarkPath addLineToPoint:CGPointMake(tileEdgeLength/2 - 2, tileEdgeLength - 5.0f)];
    [checkMarkPath addLineToPoint:CGPointMake(tileEdgeLength - 5.0f, 5.0f)];
    [checkMarkPath stroke];
    
    // 获取单个勾选框的瓦片图像
    UIImage *tileImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // 生成平铺的大尺寸图像(这里以300x300为例,可替换为你需要的尺寸)
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), NO, [UIScreen mainScreen].scale);
    [[UIColor colorWithPatternImage:tileImage] setFill];
    UIRectFill(CGRectMake(0, 0, 300, 300));
    UIImage *repeatingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return repeatingImage;
}

代码说明

  1. 先绘制单个勾选框的“瓦片”图像,确保适配Retina屏幕避免模糊;
  2. 利用UIColor colorWithPatternImage:将瓦片图像转为可平铺的颜色;
  3. 填充到目标尺寸的上下文,得到最终的重复图案图像。

方案2:直接将图案设为视图背景

如果你的需求是给某个UIView设置这种重复勾选框背景,不需要单独生成UIImage,可以简化步骤:

// 先创建单个勾选框瓦片(复用方案1里的tileImage生成逻辑)
UIImage *checkTile = [self createSingleCheckmarkTile];
// 直接设置视图背景色为平铺图案
UIView *patternView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 200)];
patternView.backgroundColor = [UIColor colorWithPatternImage:checkTile];
[self.view addSubview:patternView];

实用建议

  • 样式自定义:调整tileEdgeLength、线宽、颜色值,或者修改勾选标记的路径,就能匹配你需要的设计风格;
  • 性能优化:如果这个图案是静态使用的,建议提前生成并缓存图像,不要每次需要都重新绘制;
  • 状态适配:如果需要混合勾选/未勾选的样式,可以制作两种不同的瓦片图像,通过UIBezierPath或者CALayer组合,或者使用蒙版实现;
  • Retina适配:始终使用UIGraphicsBeginImageContextWithOptions并传入屏幕scale,保证图像清晰。

内容的提问来源于stack exchange,提问作者Hardik Vyas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:49:56