本文章主要我在實際開發(fā)過程中常用到的一些方法或函數(shù)掖举,未來類似功能可以直接調(diào)用或者修改即可使用。本篇將長期更新。
目錄
- UIGraphicsBeginImageContext消除鋸齒
- iOS線程
- UIbutton圖片和文字默認偏移(上下)
- 判斷設(shè)置是否越獄
- 判斷是否是數(shù)字
- 判斷是否是字符(a-z)
- 獲取當前任務(wù)占用的內(nèi)存
- 獲取中英文混合字符串的長度
- 獲取字節(jié)長度
- 獲取app的沙盒路徑
- 為Button繪制背景圖片
- 判斷空字符串
- 判斷單個文件大小
- 獲取視頻第一幀
- 獲取系統(tǒng)字體
- 比對與當前時間的天數(shù)差
- 色值轉(zhuǎn)換(#2324512z轉(zhuǎn)UIColor)
- 通過顏色設(shè)置圖片
- 通過顏色設(shè)置圖片(有高度)
- 將圖片轉(zhuǎn)換為黑白
- 緩存圖片到本地 (注意:需要指定緩存路徑,獲取到本地沙盒路徑等)敞曹。
- 圖片裁剪(傳入Rect)
- 按尺寸壓縮圖片
- 設(shè)置陰影
- 價格轉(zhuǎn)換為每隔3位用逗號分割
ARC && MRC 使用
- ARC環(huán)境中引入MRC文件 加入
-fno-objc-arc
- MRC環(huán)境引入ARC文件,加入:
-fobjc-arc
- UIGraphicsBeginImageContext消除鋸齒
最近在做連線的時候發(fā)現(xiàn)综膀,斜線會有鋸齒存在澳迫。查閱資料發(fā)現(xiàn)是像素點原因引起,以下只是簡單解決的一種方式剧劝,有一定效果但不全面纲刀。僅做記錄。
//方法1
view.layer.contentsScale = [[UIScreen mainScreen] scale];
//方法2
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(context,true);//開啟自動去鋸齒
CGContextSetShouldAntialias(context, true);
- iOS線程
一般來說,隊列可分為兩種類型:串行和并行示绊。也可以分為系統(tǒng)隊列和用戶隊列兩種
串行:
dispatch_get_main_queue() 主線程隊列锭部,在主線程中執(zhí)行
dispatch_queue_create(DISPATCH_QUEUE_SERIAL) 自定義串行隊列
并行:
dispatch_get_global_queue() 由系統(tǒng)維護的并行隊列
dispatch_queue_create(DISPATCH_QUEUE_CONCURRENT) 自定義并發(fā)隊列
This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.
該函數(shù)為向dispatch隊列中提交block對象的最基礎(chǔ)的機制。調(diào)用這個接口后將block提交后會馬上返回面褐,并不會等待block被調(diào)用拌禾。參數(shù)queue決定block對象是被串行執(zhí)行還是并行執(zhí)行。不同的串行隊列將被并行處理展哭。
示例:
//在主線程執(zhí)行一個block
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"invoke in main thread.");
});
//異步執(zhí)行一個block
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"invoke in another thread which is in system thread pool.");
});
- UIbutton圖片和文字默認偏移(上下)
注意:傳入需要設(shè)置的Button和文字和圖片之間的垂直距離即可湃窍。
+ (void)setButtonImageAndTitleVerticalCenterWithSpace:(CGFloat)space button:(UIButton *)button
{
CGSize imageSize = button.imageView.frame.size;
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
CGFloat totalHeight = (imageSize.height + titleSize.height + space);
button.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}
- 判斷設(shè)置是否越獄
+ (BOOL)isJailbroken {
BOOL jailbroken = NO;
NSString *cydiaPath = @"/Applications/Cydia.app";
NSString *aptPath = @"/private/var/lib/apt/";
if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) {
jailbroken = YES;
}
if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) {
jailbroken = YES;
}
return jailbroken;
}
- 判斷是否是數(shù)字
+ (BOOL) validateNumber: (NSString *) number{
NSString *reg = @"^[0-9]*$";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
return [numberTest evaluateWithObject:number];
}
- 判斷是否是字符(a-z)
+ (BOOL)validata:(NSString *)number{
NSString *regex = @"[A-Za-z]+";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [numberTest evaluateWithObject:number];
}
- 獲取當前任務(wù)占用的內(nèi)存
+ (double)usedMemory
{
task_basic_info_data_t taskInfo;
mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
kern_return_t kernReturn = task_info(mach_task_self(),
TASK_BASIC_INFO, (task_info_t)&taskInfo, &infoCount);
if(kernReturn != KERN_SUCCESS) {
return NSNotFound;
}
return taskInfo.resident_size / 1024.0 / 1024.0;
}
- 獲取中英文混合字符串的長度
+ (int)convertToInt:(NSString*)strtemp
{
int strlength = 0;
char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
if (*p) {
p++;
strlength++;
}
else {
p++;
}
}
return strlength;
}
- 獲取字節(jié)長度
+(NSUInteger) unicodeLengthOfString: (NSString *) text {
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i < text.length; i++) {
unichar uc = [text characterAtIndex: i];
asciiLength += isascii(uc) ? 1 : 2;
}
NSUInteger unicodeLength = asciiLength / 2;
if(asciiLength % 2) {
unicodeLength++;
}
return unicodeLength;
}
- 獲取app的沙盒路徑
+ (NSString *)documentPath
{
// 獲取應用程序沙盒的Documents目錄
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
return [paths objectAtIndex:0];
}
- 為Button繪制背景圖片
+ (void)backgroundTurnRedForButton:(UIButton *)button red:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha type:(int) type{
CGSize size = button.frame.size;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
view.layer.cornerRadius = 6;
view.clipsToBounds = true;
view.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
UIGraphicsBeginImageContext(size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
switch (type) {
case 0:
[button setBackgroundImage:screenImage forState:UIControlStateNormal];
break;
case 1:
[button setBackgroundImage:screenImage forState:UIControlStateHighlighted];
break;
default:
break;
}
}
- 判斷空字符串
+(BOOL) isEmptyOrNull:(NSString *) str {
if (!str) {
// null object
return YES;
} else {
NSString *trimedString = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimedString length] == 0) {
// empty string
return YES;
} else {
// is neither empty nor null
return NO;
}
}
}
- 判斷單個文件大小
+(long long)fileSizeAtPath:(NSString*)filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
- 獲取視頻第一幀
+(UIImage *)getPreViewImg:(NSString *)url
{
UIImage *img = nil;
@autoreleasepool {
NSURL *urlvideo = nil;
if([url hasPrefix:@"assets-library:"] ) {
urlvideo = [NSURL URLWithString:url];
}else{
urlvideo = [[NSURL alloc]initFileURLWithPath:url];
}
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlvideo options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
img = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
}
return img;
}
- 獲取本機IP
+ (NSString *)getIPAddress
{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while (temp_addr != NULL) {
if( temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
- 獲取系統(tǒng)字體
+ (UIFont*)getCurrentFont
{
//判斷系統(tǒng)字體的size,返回使用的字體匪傍。
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
return font;
}
- 比對與當前時間的天數(shù)差
*
*對比兩個時間
*date:需要跟當前時間對比的時間
*/
+ (int)getTimedif:(NSDate*)date
{
int num = 0;
if (!date) {
return num;
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:[NSDate date]];
NSDateComponents *dtComponents = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
num = [components day] - [dtComponents day];
return num;
}
顏色
- 色值轉(zhuǎn)換(#2324512z轉(zhuǎn)UIColor)
+ (UIColor *)hexString:(NSString *)hex{
hex = [hex stringByReplacingOccurrencesOfString:@"#" withString:@""];
if (hex.length<6) {
return nil;
}
unsigned int r,g,b;
NSRange stringRange;
stringRange.length = 2;
stringRange.location = 0;
[[NSScanner scannerWithString:[hex substringWithRange:stringRange]] scanHexInt:&r];
stringRange.location = 2;
[[NSScanner scannerWithString:[hex substringWithRange:stringRange]] scanHexInt:&g];
stringRange.location = 4;
[[NSScanner scannerWithString:[hex substringWithRange:stringRange]] scanHexInt:&b];
float fr = (r * 1.0f) / 255.0f;
float fg = (g * 1.0f) / 255.0f;
float fb = (b * 1.0f) / 255.0f;
return [UIColor colorWithRed:fr green:fg blue:fb alpha:1.0f];
}
- 通過顏色設(shè)置圖片
+ (UIImage *)createImageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
- 通過顏色設(shè)置圖片(有高度)
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
UIGraphicsBeginImageContext(r.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, r);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
圖片處理
- 裁剪圖片為圓形
+(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
UIGraphicsBeginImageContext(image.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 20);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);
[image drawInRect:rect];
CGContextAddEllipseInRect(context, rect);
CGContextStrokePath(context);
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
- 為圖片添加圓角顯示
//給圖片添加圓角顯示
+ (UIImage *) roundCorners: (UIImage*) img
{
int w = img.size.width;
int h = img.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextBeginPath(context);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
addRoundedRectToPath(context, rect, 10, 10);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
UIImage *images = [UIImage imageWithCGImage:imageMasked];
CGImageRelease(imageMasked);
return images;
}
- 將圖片轉(zhuǎn)換為黑白
+ (UIImage*)blackAndWhitePhoto:(UIImage*)anImage
{
CGImageRef imageRef = anImage.CGImage;
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
size_t bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
bool shouldInterpolate = CGImageGetShouldInterpolate(imageRef);
CGColorRenderingIntent intent = CGImageGetRenderingIntent(imageRef);
CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef);
CFDataRef data = CGDataProviderCopyData(dataProvider);
UInt8 *buffer = (UInt8*)CFDataGetBytePtr(data);
NSUInteger x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
UInt8 *tmp;
tmp = buffer + y * bytesPerRow + x * 4;
UInt8 red,green,blue;
red = *(tmp + 0);
green = *(tmp + 1);
blue = *(tmp + 2);
UInt8 brightness;
brightness = (77 * red + 28 * green + 151 * blue) / 256;
*(tmp + 0) = brightness;
*(tmp + 1) = brightness;
*(tmp + 2) = brightness;
}
}
CFDataRef effectedData = CFDataCreate(NULL, buffer, CFDataGetLength(data));
CGDataProviderRef effectedDataProvider = CGDataProviderCreateWithCFData(effectedData);
CGImageRef effectedCgImage = CGImageCreate(
width, height,
bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpace, bitmapInfo, effectedDataProvider,
NULL, shouldInterpolate, intent);
UIImage *effectedImage = [[UIImage alloc] initWithCGImage:effectedCgImage];
CGImageRelease(effectedCgImage);
CFRelease(effectedDataProvider);
CFRelease(effectedData);
CFRelease(data);
return effectedImage;
}
- 緩存圖片到本地
注意:需要指定緩存路徑您市,獲取到本地沙盒路徑等。
+ (void)saveImageimageData:(NSData *)imgData
{
NSString *path = @"chat/Image_send/";
if (![[NSFileManager defaultManager]fileExistsAtPath:[[LX_Sandbox docPath] stringByAppendingPathComponent:path]])
[[NSFileManager defaultManager]createDirectoryAtPath:[[LX_Sandbox docPath]stringByAppendingPathComponent:path] withIntermediateDirectories:YES attributes:nil error:nil];
NSString *imgPath = [[[LX_Sandbox docPath]stringByAppendingPathComponent:path]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[Function getSendMessageTime]]];
if ([[NSFileManager defaultManager]fileExistsAtPath:imgPath]) {
[[NSFileManager defaultManager]removeItemAtPath:imgPath error:nil];
}
if ([[NSFileManager defaultManager]createFileAtPath:imgPath contents:nil attributes:nil]) {
[imgData writeToFile:imgPath atomically:YES];
}
}
- 圖片裁剪(傳入Rect)
+(UIImage *)imageCropping:(UIImage*)image rect:(CGRect)rect{
CGImageRef cr = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:cr];
CGImageRelease(cr);
return cropped;
}
- 按尺寸壓縮圖片
+ (UIImage*)scaleFromImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
UIImage* newImage = nil;
@autoreleasepool {
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if(width <= newSize.width && height <= newSize.height){
return image;
}
if(width == 0 || height == 0){
return image;
}
CGFloat widthFactor = newSize.width / width;
CGFloat heightFactor = newSize.height / height;
CGFloat scaleFactor = (widthFactor<heightFactor?widthFactor:heightFactor);
CGFloat scaledWidth = width * scaleFactor;
CGFloat scaledHeight = height * scaleFactor;
CGSize targetSize = CGSizeMake(scaledWidth,scaledHeight);
UIGraphicsBeginImageContext(targetSize);
[image drawInRect:CGRectMake(0,0,targetSize.width,targetSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newImage;
}
- 陰影
/// 設(shè)置陰影
/// @param layer 陰影作用layer
/// @param offset 偏移量
/// @param cornerRadius layer半徑
/// @param shadowRadius 陰影半徑
/// @param shadowOpacity 陰影透明度
/// @param shadowColor 陰影顏色
/// @param backgroundColor 背景色
- (void)setShadowWithLayer:(CALayer *)layer offset:(CGSize)offset cornerRadius:(CGFloat)cornerRadius shadowRadius:(CGFloat)shadowRadius shadowOpacity:(CGFloat)shadowOpacity shadowColor:(UIColor *)shadowColor backgroundColor:(UIColor *)backgroundColor{
layer.backgroundColor = backgroundColor.CGColor;
layer.shadowOpacity = shadowOpacity;//陰影透明度
layer.shadowColor = shadowColor.CGColor;//陰影顏色
layer.shadowOffset = offset;//陰影偏移量
layer.shadowRadius = shadowRadius;//模糊計算半徑
layer.cornerRadius = cornerRadius;
layer.masksToBounds = NO;
}
- 價格轉(zhuǎn)換為每隔3位用逗號分割
/**
價格轉(zhuǎn)換為每隔3位用逗號分割
show 是否顯示小數(shù)點后面
*/
- (NSString *)changePriceWithNumber:(float)value showPoint:(BOOL)show {
NSString *valueStr = @"";
NSString *format = @"";
if (show) {
valueStr = [NSString stringWithFormat:@"%.2f", value];
format = @",###.##";
} else {
valueStr = [NSString stringWithFormat:@"%.f", value];
format = @",###";
}
NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:valueStr];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setPositiveFormat:format];
return [numberFormatter stringFromNumber:decNumber];
}