SDWebImage 加載大量高清圖片時內存暴增web
static BOOL SDImageCacheOldShouldDecompressImages = YES; static BOOL SDImagedownloderOldShouldDecompressImages = YES; - (void)viewDidLoad { [super viewDidLoad]; // 關閉SD加載高清大圖時的解壓縮 SDImageCache *canche = [SDImageCache sharedImageCache]; SDImageCacheOldShouldDecompressImages = canche.shouldDecompressImages; canche.shouldDecompressImages = NO; SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader]; SDImagedownloderOldShouldDecompressImages = downloder.shouldDecompressImages; downloder.shouldDecompressImages = NO; } -(void)dealloc { SDImageCache *canche = [SDImageCache sharedImageCache]; canche.shouldDecompressImages = SDImageCacheOldShouldDecompressImages; SDWebImageDownloader *downloder = [SDWebImageDownloader sharedDownloader]; downloder.shouldDecompressImages = SDImagedownloderOldShouldDecompressImages; }
[UIApplication sharedApplication].idleTimerDisabled = YES;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 若是是你須要隱藏的那一行,返回高度爲0 if(indexPath.row == YouWantToHideRow){ return 0; } return 44; } // 而後再你須要隱藏cell的時候調用 [self.tableView beginUpdates]; [self.tableView endUpdates];
button.adjustsImageWhenHighlighted = NO; 或者在建立的時候 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:.5f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ BOOL oldState = [UIView areAnimationsEnabled]; [UIView setAnimationsEnabled:NO]; [UIApplication sharedApplication].keyWindow.rootViewController = [[RootViewController alloc]init]; [UIView setAnimationsEnabled:oldState]; } completion:^(BOOL finished) { }];
NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
編譯的時候遇到 no such file or directory: /users/apple/XXXwindows
// 必須寫的方法,和editActionsForRowAtIndexPath配對使用,裏面什麼不寫也行 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { }
NSSystemTimeZoneDidChangeNotification監聽修改時間界面的兩個按鈕狀態變化 UIApplicationSignificantTimeChangeNotification 監聽用戶改變時間 (只要點擊自動設置按鈕就會調用) NSSystemClockDidChangeNotification 監聽用戶修改時間(時間不一樣纔會調用)
[self.collectionView layoutIfNeeded];//添加這句話就好 QTMResContinueEditeCell *cell = (QTMResContinueEditeCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_index inSection:0]];
// 跳進app設置 if (UIApplicationOpenSettingsURLString != NULL) { UIApplication *application = [UIApplication sharedApplication]; NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) { [application openURL:URL options:@{} completionHandler:nil]; } else { [application openURL:URL]; } }
- (UIImage *)cutImageWithView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
collectionView.alwaysBounceHorizontal = YES; collectionView.alwaysBounceVertical = YES;
+ (UIImage *)imageWithColor:(UIColor *)color { //描述一個矩形 CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); //開啓圖形上下文 UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0); //得到圖形上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); //使用color演示填充上下文 CGContextSetFillColorWithColor(ctx, [color CGColor]); //渲染上下文 CGContextFillRect(ctx, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); //關閉圖形上下文 UIGraphicsEndImageContext(); return image; }
#define ViewBorderRadius(View, Radius, Width, Color)\ \ [View.layer setCornerRadius:(Radius)];\ [View.layer setMasksToBounds:YES];\ [View.layer setBorderWidth:(Width)];\ [View.layer setBorderColor:[Color CGColor]] // view圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.whiteView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = self.whiteView.bounds; maskLayer.path = maskPath.CGPath; self.whiteView.layer.mask = maskLayer; ##指定了須要成爲圓角的角該參數是UIRectCorner類型的,可選的值有: * UIRectCornerTopLeft * UIRectCornerTopRight * UIRectCornerBottomLeft * UIRectCornerBottomRight * UIRectCornerAllCorners
#define DegreesToRadian(x) (M_PI * (x) / 180.0)
#define RadianToDegrees(radian) (radian*180.0)/(M_PI)
//建議使用前兩種宏定義,性能高於後者 #define LOADIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]] #define IMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]] #define ImageNamed(_pointer) [UIImage imageNamed:[UIUtil imageName:_pointer]] #define UIImageName(name) [UIImage imageNamed:name]
//獲取temp #define PathTemp NSTemporaryDirectory() //獲取Document #define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] //獲取 Cache #define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//DEBUG 模式下打印日誌,當前行 #ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif //重寫NSLog,Debug模式下打印日誌和當前行數 #if DEBUG #define NSLog(FORMAT, ...) fprintf(stderr,"\nfunction:%s line:%d content:%s\n", __FUNCTION__, __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]); #else #define NSLog(FORMAT, ...) nil #endif //DEBUG 模式下打印日誌,當前行 並彈出一個警告 #ifdef DEBUG # define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } #else # define ULog(...) #endif
#define FONTS(size) [UIFont systemFontOfSize:(size)] #define BOLDFONTS(size) [UIFont boldSystemFontOfSize:(size)]
//主線程 #define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock); //異步線程 #define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);
#define NOTIF_ADD(n, f) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(f) name:n object:nil] #define NOTIF_POST(n, o) [[NSNotificationCenter defaultCenter] postNotificationName:n object:o] #define NOTIF_REMV() [[NSNotificationCenter defaultCenter] removeObserver:self]
// RGB顏色轉換(16進制->10進制) #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] // 獲取RGB顏色 #define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a] //清除背景色 #define CLEARCOLOR [UIColor clearColor] // 隨機色 #define RandomCOLOR RGBCOLOR(arc4random_uniform(256),arc4random_uniform(256),arc4random_uniform(256))
+(UIWindow*)getWindow { UIWindow* win = nil; //[UIApplication sharedApplication].keyWindow; for (id item in [UIApplication sharedApplication].windows) { if ([item class] == [UIWindow class]) { if (!((UIWindow*)item).hidden) { win = item; break; } } } return win; }
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"]; // 或者 textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13],NSForegroundColorAttributeName : [UIColor grayColor]}];
/** * 存 數組數據*/ +(void)setObectOfArray:(NSArray *)array fileName:(NSString *)fileName { //緩存文件的 根路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // 緩存 文件夾 路徑 NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:filePath] == NO) { [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; } //緩存文件的路徑 NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]]; BOOL isSuccess = [array writeToFile:cacheFilePath atomically:NO]; if (isSuccess) { NSLog(@"緩存數據成功:---%@",cacheFilePath); }else { NSLog(@"緩存數據失敗:---%@",cacheFilePath); } } /*** 取 數組數據*/ +(NSArray *)cacheArrayForFileName:(NSString *)fileName { //緩存文件的 根路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // 緩存 文件夾 路徑 NSString *filePath = [path stringByAppendingPathComponent:@"XXX.dataCache"]; //緩存文件的路徑 NSString * cacheFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",fileName]]; //取得緩存文件 NSArray *array = [NSArray arrayWithContentsOfFile:cacheFilePath]; return array; } /*** 清除 這個所有的緩存數據 */ +(void)clearCacheListData:(void (^)())completion { // 異線程 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 清楚緩存 //緩存文件的 根路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // 緩存 文件夾 路徑 NSString *filePath = [path stringByAppendingPathComponent:@"FortuneDonkey.dataCache"]; NSFileManager *manager = [NSFileManager defaultManager]; //移除文件夾 [manager removeItemAtPath:filePath error:nil]; // 建立一個新的文件夾 [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; if (completion) { //回調主線程 dispatch_async(dispatch_get_main_queue(), ^{ completion(); }); } }); } /*** 清除SD緩存數據 */ -(void)clearSDCacheData { //先清除內存中的圖片緩存 [[SDImageCache sharedImageCache] clearMemory]; //清除磁盤的緩存 [[SDImageCache sharedImageCache] clearDisk]; }
- (CGFloat)getCachSize { NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize]; //獲取自定義緩存大小 //用枚舉器遍歷 一個文件夾的內容 //1.獲取 文件夾枚舉器 NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"]; NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath]; __block NSUInteger count = 0; //2.遍歷 for (NSString *fileName in enumerator) { NSString *path = [myCachePath stringByAppendingPathComponent:fileName]; NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]; count += fileDict.fileSize;//自定義全部緩存大小 } // 獲得是字節 轉化爲M CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024; return totalSize; }
if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) { NSLog(@"沒有定位權限"); } AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (statusVideo == AVAuthorizationStatusDenied) { NSLog(@"沒有攝像頭權限"); } //是否有麥克風權限 AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]; if (statusAudio == AVAuthorizationStatusDenied) { NSLog(@"沒有錄音權限"); } [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusDenied) { NSLog(@"沒有相冊權限"); } }];
//獲取系統版本 #define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue] #define IS_IOS10_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) //獲取當前語言 #define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0]) //判斷是否 Retina屏、設備是否%fhone 五、是不是iPad #define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO) #define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) #define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO) #define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //判斷是真機仍是模擬器 #if TARGET_OS_IPHONE //iPhone Device #endif #if TARGET_IPHONE_SIMULATOR //iPhone Simulator #endif
- (void)viewDidLoad { [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]]; } - (void)pasteBoard:(UILongPressGestureRecognizer *)longPress { if (longPress.state == UIGestureRecognizerStateBegan) { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = @"我是文字"; } }
//經過圖片 Data 數據第一個字節 來獲取圖片擴展名 - (NSString *)contentTypeForImageData:(NSData *)data { uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @"jpeg"; case 0x89: return @"png"; case 0x47: return @"gif"; case 0x49: case 0x4D: return @"tiff"; case 0x52: if ([data length] < 12) { return nil; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return @"webp"; } return nil; } return nil; }
//手機序列號 NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier]; //手機別名: 用戶定義的名稱 NSString* userPhoneName = [[UIDevice currentDevice] name]; //設備名稱 NSString* deviceName = [[UIDevice currentDevice] systemName]; //手機系統版本 NSString* phoneVersion = [[UIDevice currentDevice] systemVersion]; //手機型號 NSString* phoneModel = [[UIDevice currentDevice] model]; //地方型號 (國際化區域名稱) NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel]; NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; // 當前應用名稱 NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"]; // 當前應用版本 NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; // 當前應用版本號碼 int類型 NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
- (UIImage *)circleImage { // NO表明透明 UIGraphicsBeginImageContextWithOptions(self.size, NO, 1); // 得到上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 添加一個圓 CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); // 方形變圓形 CGContextAddEllipseInRect(ctx, rect); // 裁剪 CGContextClip(ctx); // 將圖片畫上去 [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
CGFloat fixelW = CGImageGetWidth(image.CGImage); CGFloat fixelH = CGImageGetHeight(image.CGImage);
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString { NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil]; return responseJSON; }
//獲取當前屏幕顯示的viewcontroller - (UIViewController *)getCurrentVC{ UIWindow *window = [[UIApplication sharedApplication].windows firstObject]; if (!window) { return nil; } UIView *tempView; for (UIView *subview in window.subviews) { if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) { tempView = subview; break; } } if (!tempView) { tempView = [window.subviews lastObject]; } id nextResponder = [tempView nextResponder]; while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) { tempView = [tempView.subviews firstObject]; if (!tempView) { return nil; } nextResponder = [tempView nextResponder]; } return (UIViewController *)nextResponder; }
// 添加監聽者 [self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil]; // 當監聽的屬性值變化的時候會來到這個方法 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"property"]) { [self textViewTextChange]; } else { } }
NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus]; if (status == NotReachable) { NSLog(@"當前設備無網絡"); } if (status == ReachableViaWiFi) { NSLog(@"當前wifi網絡"); } if (status == ReachableViaWWAN) { NSLog(@"當前蜂窩移動網絡"); }
// 監聽網絡情況 AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager]; [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusUnknown: break; case AFNetworkReachabilityStatusNotReachable: { NSLog(@"當前設備無網絡"); } break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"當前wifi網絡"); break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"當前蜂窩移動網絡"); break; default: break; } }]; [mgr startMonitoring];
self.view.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.7f];
取圖片某一點的顏色數組
if (point.x < 0 || point.y < 0) return nil; CGImageRef imageRef = self.CGImage; NSUInteger width = CGImageGetWidth(imageRef); NSUInteger height = CGImageGetHeight(imageRef); if (point.x >= width || point.y >= height) return nil; unsigned char *rawData = malloc(height * width * 4); if (!rawData) return nil; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); NSUInteger bytesPerPixel = 4; NSUInteger bytesPerRow = bytesPerPixel * width; NSUInteger bitsPerComponent = 8; CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (!context) { free(rawData); return nil; } CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); CGContextRelease(context); int byteIndex = (bytesPerRow * point.y) + point.x * bytesPerPixel; CGFloat red = (rawData[byteIndex] * 1.0) / 255.0; CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0; CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0; CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0; UIColor *result = nil; result = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; free(rawData); return result;
- (BOOL)hasAlphaChannel { CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage); return (alpha == kCGImageAlphaFirst || alpha == kCGImageAlphaLast || alpha == kCGImageAlphaPremultipliedFirst || alpha == kCGImageAlphaPremultipliedLast); }
+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage { CGImageRef firstImageRef = firstImage.CGImage; CGFloat firstWidth = CGImageGetWidth(firstImageRef); CGFloat firstHeight = CGImageGetHeight(firstImageRef); CGImageRef secondImageRef = secondImage.CGImage; CGFloat secondWidth = CGImageGetWidth(secondImageRef); CGFloat secondHeight = CGImageGetHeight(secondImageRef); CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight)); UIGraphicsBeginImageContext(mergedSize); [firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)]; [secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }
// 畫水印 - (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) { UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0); } //原圖 [image drawInRect:self.bounds]; //水印圖 [mark drawInRect:rect]; UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.image = newPic; }
自定義UILabel // 重寫label的textRectForBounds方法 - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines { CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; switch (self.textAlignmentType) { case WZBTextAlignmentTypeLeftTop: { rect.origin = bounds.origin; } break; case WZBTextAlignmentTypeRightTop: { rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y); } break; case WZBTextAlignmentTypeLeftBottom: { rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeRightBottom: { rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeTopCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y); } break; case WZBTextAlignmentTypeBottomCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height); } break; case WZBTextAlignmentTypeLeft: { rect.origin = CGPointMake(0, rect.origin.y); } break; case WZBTextAlignmentTypeRight: { rect.origin = CGPointMake(rect.origin.x, 0); } break; case WZBTextAlignmentTypeCenter: { rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2); } break; default: break; } return rect; } - (void)drawTextInRect:(CGRect)rect { CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines]; [super drawTextInRect:textRect]; }
+ (NSString *)removeSpaceAndNewline:(NSString *)str { NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""]; temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""]; temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""]; return temp; }
+ (BOOL)isBlank:(NSString *)str { NSRange _range = [str rangeOfString:@" "]; if (_range.location != NSNotFound) { //有空格 return YES; } else { //沒有空格 return NO; } }
NSURL *url = [NSURL URLWithString:filepath]; AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil]; AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1]; generate1.appliesPreferredTrackTransform = YES; NSError *err = NULL; CMTime time = CMTimeMake(1, 2); CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err]; UIImage *one = [[UIImage alloc] initWithCGImage:oneRef]; return one;
+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString { NSURL *videoUrl = [NSURL URLWithString:urlString]; AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl]; CMTime time = [avUrl duration]; int seconds = ceil(time.value/time.timescale); return seconds; }
self.tableView.tableHeaderView = [UIView new]; self.tableView.tableFooterView = [UIView new];
isKindOfClass能夠判斷某個對象是否屬於某個類,或者這個類的子類。 isMemberOfClass更加精準,它只能判斷這個對象類型是否爲這個類(不能判斷子類)
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self; } } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil; } } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { return NO; }
子類化UILabel,重寫drawTextInRect方法 - (void)drawTextInRect:(CGRect)rect { // 邊距,上左下右 UIEdgeInsets insets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }
子類化UILabel,重寫drawTextInRect方法 - (void)drawTextInRect:(CGRect)rect { CGContextRef c = UIGraphicsGetCurrentContext(); // 設置描邊寬度 CGContextSetLineWidth(c, 1); CGContextSetLineJoin(c, kCGLineJoinRound); CGContextSetTextDrawingMode(c, kCGTextStroke); // 描邊顏色 self.textColor = [UIColor redColor]; [super drawTextInRect:rect]; // 文本顏色 self.textColor = [UIColor yellowColor]; CGContextSetTextDrawingMode(c, kCGTextFill); [super drawTextInRect:rect]; }
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr{ // CAGradientLayer類對其繪製漸變背景顏色、填充層的形狀(包括圓角) CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = view.bounds; // 建立漸變色數組,須要轉換爲CGColor顏色 gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString:toHexColorStr].CGColor]; // 設置漸變顏色方向,左下點爲(0,0), 右上點爲(1,1) gradientLayer.startPoint = CGPointMake(0, 0.5); gradientLayer.endPoint = CGPointMake(1, 0.5); // 設置顏色變化點,取值範圍 0.0~1.0 gradientLayer.locations = @[@0,@1]; return gradientLayer; }
// 左上角和右下角添加圓角 UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.frame = view.bounds; maskLayer.path = maskPath.CGPath; view.layer.mask = maskLayer;
// view分類方法 - (NSString *)encodeToBase64String:(UIImage *)image { return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; } - (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; }
[webView setBackgroundColor:[UIColor clearColor]]; [webView setOpaque:NO];
// 分割線顏色 [self.tableView setSeparatorColor:[UIColor myColor]]; // 頂到頭 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { [cell setSeparatorInset:UIEdgeInsetsZero]; [cell setLayoutMargins:UIEdgeInsetsZero]; cell.preservesSuperviewLayoutMargins = NO; } - (void)viewDidLayoutSubviews { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; [self.tableView setLayoutMargins:UIEdgeInsetsZero]; }
CAShapeLayer *border = [CAShapeLayer layer]; border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor; border.fillColor = nil; border.lineDashPattern = @[@4, @2]; border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath; border.frame = view.bounds; [view.layer addSublayer:border];
// 繼承UITextView重寫這個方法 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { // 返回NO爲禁用,YES爲開啓 // 粘貼 if (action == @selector(paste:)) return NO; // 剪切 if (action == @selector(cut:)) return NO; // 複製 if (action == @selector(copy:)) return NO; // 選擇 if (action == @selector(select:)) return NO; // 選中所有 if (action == @selector(selectAll:)) return NO; // 刪除 if (action == @selector(delete:)) return NO; // 分享 if (action == @selector(share)) return NO; return [super canPerformAction:action withSender:sender]; }