整理一些iOS常用到的代码片段

1:截图(Layer)

- (UIImage *)snapshotImage {

    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    [self renderInContext:context];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

2:截图为PDF格式(Layer)

- (NSData *)snapshotPDF {

    CGRect bounds = self.bounds;

    NSMutableData* data = [NSMutableData data];

    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);

    CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);

    CGDataConsumerRelease(consumer);

    if (!context) return nil;

    CGPDFContextBeginPage(context, NULL);

    CGContextTranslateCTM(context, 0, bounds.size.height);

    CGContextScaleCTM(context, 1.0, -1.0);

    [self renderInContext:context];

    CGPDFContextEndPage(context);

    CGPDFContextClose(context);

    CGContextRelease(context);

    return data;

}

3:获取沙盒路径

- (NSURL *)documentsURL {

    return [[[NSFileManager defaultManager]

             URLsForDirectory:NSDocumentDirectory

             inDomains:NSUserDomainMask] lastObject];

}


- (NSString *)documentsPath {

    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

}


4:CPU,内存使用状态

- (int64_t)memoryUsage {

    struct task_basic_info info;

    mach_msg_type_number_t size = sizeof(info);

    kern_return_t kern = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);

    if (kern != KERN_SUCCESS) return -1;

    return info.resident_size;

}


- (float)cpuUsage {

    kern_return_t kr;

    task_info_data_t tinfo;

    mach_msg_type_number_t task_info_count;

    

    task_info_count = TASK_INFO_MAX;

    kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);

    if (kr != KERN_SUCCESS) {

        return -1;

    }

    

    thread_array_t thread_list;

    mach_msg_type_number_t thread_count;

    

    thread_info_data_t thinfo;

    mach_msg_type_number_t thread_info_count;

    

    thread_basic_info_t basic_info_th;

    

    kr = task_threads(mach_task_self(), &thread_list, &thread_count);

    if (kr != KERN_SUCCESS) {

        return -1;

    }

    

    long tot_sec = 0;

    long tot_usec = 0;

    float tot_cpu = 0;

    int j;

    

    for (j = 0; j < thread_count; j++) {

        thread_info_count = THREAD_INFO_MAX;

        kr = thread_info(thread_list[j], THREAD_BASIC_INFO,

                         (thread_info_t)thinfo, &thread_info_count);

        if (kr != KERN_SUCCESS) {

            return -1;

        }

        

        basic_info_th = (thread_basic_info_t)thinfo;

        

        if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {

            tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;

            tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;

            tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE;

        }

    }

    

    kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));

    assert(kr == KERN_SUCCESS);

    

    return tot_cpu;

}

5:获取字符串的贝塞尔曲线


+ (UIBezierPath *)bezierPathWithText:(NSString *)text font:(UIFont *)font {

    CTFontRef ctFont = font.CTFontRef;

    if (!ctFont) return nil;

    NSDictionary *attrs = @{ (__bridge id)kCTFontAttributeName:(__bridge id)ctFont };

    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attrs];

    CFRelease(ctFont);

    

    CTLineRef line = CTLineCreateWithAttributedString((__bridge CFTypeRef)attrString);

    if (!line) return nil;

    

    CGMutablePathRef cgPath = CGPathCreateMutable();

    CFArrayRef runs = CTLineGetGlyphRuns(line);

    for (CFIndex iRun = 0, iRunMax = CFArrayGetCount(runs); iRun < iRunMax; iRun++) {

        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, iRun);

        CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);

        

        for (CFIndex iGlyph = 0, iGlyphMax = CTRunGetGlyphCount(run); iGlyph < iGlyphMax; iGlyph++) {

            CFRange glyphRange = CFRangeMake(iGlyph, 1);

            CGGlyph glyph;

            CGPoint position;

            CTRunGetGlyphs(run, glyphRange, &glyph);

            CTRunGetPositions(run, glyphRange, &position);

            

            CGPathRef glyphPath = CTFontCreatePathForGlyph(runFont, glyph, NULL);

            if (glyphPath) {

                CGAffineTransform transform = CGAffineTransformMakeTranslation(position.x, position.y);

                CGPathAddPath(cgPath, &transform, glyphPath);

                CGPathRelease(glyphPath);

            }

        }

    }

    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:cgPath];

    CGRect boundingBox = CGPathGetPathBoundingBox(cgPath);

    CFRelease(cgPath);

    CFRelease(line);

    

    [path applyTransform:CGAffineTransformMakeScale(1.0, -1.0)];

    [path applyTransform:CGAffineTransformMakeTranslation(0.0, boundingBox.size.height)];

    

    return path;

}

6:根据颜色生成纯色图片


+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {

    if (!color || size.width <= 0 || size.height <= 0) return nil;

    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);

    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);

    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

7:改变图片frame

- (UIImage *)imageByResizeToSize:(CGSize)size contentMode:(UIViewContentMode)contentMode {

    if (size.width <= 0 || size.height <= 0) return nil;

    UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);

    [self drawInRect:CGRectMake(0, 0, size.width, size.height) withContentMode:contentMode clipsToBounds:NO];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

8:利用CPU绘制圆角Image

- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius

                              corners:(UIRectCorner)corners

                          borderWidth:(CGFloat)borderWidth

                          borderColor:(UIColor *)borderColor

                       borderLineJoin:(CGLineJoin)borderLineJoin {

    

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

    CGContextRef context = UIGraphicsGetCurrentContext();

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

    CGContextScaleCTM(context, 1, -1);

    CGContextTranslateCTM(context, 0, -rect.size.height);

    

    CGFloat minSize = MIN(self.size.width, self.size.height);

    if (borderWidth < minSize / 2) {

        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(radius, borderWidth)];

        [path closePath];

        

        CGContextSaveGState(context);

        [path addClip];

        CGContextDrawImage(context, rect, self.CGImage);

        CGContextRestoreGState(context);

    }

    

    if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) {

        CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale;

        CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset);

        CGFloat strokeRadius = radius > self.scale / 2 ? radius - self.scale / 2 : 0;

        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, borderWidth)];

        [path closePath];

        

        path.lineWidth = borderWidth;

        path.lineJoinStyle = borderLineJoin;

        [borderColor setStroke];

        [path stroke];

    }

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值