- 判斷郵箱格式是否正確的代碼
-(BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
return [emailTest evaluateWithObject:email];
}
- 判斷是否有特殊字符
+(BOOL)isContainsSpecialCharacters:(NSString *)string{
NSString *regex = @".*[-`=\\\[\\];',./~!@#$%^&*()_+|{}:\"<>?]+.*";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicate evaluateWithObject:string]==YES) {
return YES;
}else{
return NO;
}
}
- 判斷是否包含漢字
+(BOOL)isChinese:(NSString *)str {
for(int i=0; i< [str length];i++){
int a = [str characterAtIndex:i]; if( a > 0x4e00 && a < 0x9fff){
return YES;
}
}
return NO;
}
- 身份證號碼驗證
#pragma mark -身份證號全校驗
+ (BOOL)verifyIDCardNumber:(NSString *)IDCardNumber
{
IDCardNumber = [IDCardNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([IDCardNumber length] != 18)
{
return NO;
}
NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
NSString *leapMmdd = @"0229";
NSString *year = @"(19|20)[0-9]{2}";
NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd , @"[0-9]{3}[0-9Xx]"];
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if (![regexTest evaluateWithObject:IDCardNumber])
{
return NO;
}
int summary = ([IDCardNumber substringWithRange:NSMakeRange(0,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(10,1)].intValue) *7
+ ([IDCardNumber substringWithRange:NSMakeRange(1,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(11,1)].intValue) *9
+ ([IDCardNumber substringWithRange:NSMakeRange(2,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(12,1)].intValue) *10
+ ([IDCardNumber substringWithRange:NSMakeRange(3,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(13,1)].intValue) *5
+ ([IDCardNumber substringWithRange:NSMakeRange(4,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(14,1)].intValue) *8
+ ([IDCardNumber substringWithRange:NSMakeRange(5,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(15,1)].intValue) *4
+ ([IDCardNumber substringWithRange:NSMakeRange(6,1)].intValue + [IDCardNumber substringWithRange:NSMakeRange(16,1)].intValue) *2
+ [IDCardNumber substringWithRange:NSMakeRange(7,1)].intValue *1 + [IDCardNumber substringWithRange:NSMakeRange(8,1)].intValue *6
+ [IDCardNumber substringWithRange:NSMakeRange(9,1)].intValue *3;
NSInteger remainder = summary % 11;
NSString *checkBit = @"";
NSString *checkString = @"10X98765432";
checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判斷校驗位
return [checkBit isEqualToString:[[IDCardNumber substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}
-
判斷字符串是否為空
+(NSString *)stringIsEmpty:(NSString *)str{NSString *string=[NSString stringWithFormat:@"%@",str];
if ([string isEqualToString:@""]||[string isEqualToString:@"(null)"]||[string isEqualToString:@"<null>"]||string==nil||[string isEqual:[NSNull class]]) {
string=@"";}
return string;
} 壓縮圖片
/**
* 實現(xiàn)圖片的縮小或者放大
*
* @param size 大小范圍
*
* @return 新的圖片
*/
-(UIImage*)scaleImageWithSize:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size,NO,0); //size 為CGSize類型,即你所需要的圖片尺寸
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage; //返回的就是已經(jīng)改變的圖片
}
- 讓網(wǎng)絡(luò)加載圖片有個動畫效果(前提是導(dǎo)入了SDWebImage)
-(void)animationWithImage:(NSString *)imageName
{
[self sd_setImageWithURL:[NSURL URLWithString:imageName] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image && cacheType == SDImageCacheTypeNone)
{
self.alpha = 0;
[UIView animateWithDuration:0.5 animations:^{
self.alpha = 1.0f;
}];
}
else
{
self.alpha = 1.0f;
}
}];
}
- 根據(jù)字符串的長度計算高度
+ (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxWidth:(CGFloat)maxWidth
{
NSDictionary *attributesDict = @{NSFontAttributeName:FONT(font)};
CGSize maxSize = CGSizeMake(maxWidth, MAXFLOAT);
CGRect subviewRect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil];
return subviewRect.size;
}
- 拼接屬性字符串,在電商類應(yīng)用用的比較多(比如價格,市場價和銷售價,此時可以用一個lable搞定,而不用兩個label)
+(NSAttributedString *)recombinePrice:(CGFloat)CNPrice orderPrice:(CGFloat)unitPrice
{
NSMutableAttributedString *mutableAttributeStr = [[NSMutableAttributedString alloc] init];
NSAttributedString *string1 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%.f",unitPrice] attributes:@{NSForegroundColorAttributeName : [UIColor redColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:12]}];
NSAttributedString *string2 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%.f",CNPrice] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:11],NSStrikethroughStyleAttributeName :@(NSUnderlineStyleSingle),NSStrikethroughColorAttributeName : [UIColor lightGrayColor]}];
[mutableAttributeStr appendAttributedString:string1];
[mutableAttributeStr appendAttributedString:string2];
return mutableAttributeStr;
}
- 調(diào)整label行間距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = lineSpace; // 調(diào)整行間距
NSRange range = NSMakeRange(0, [string length]);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
return attributedString;
}
- 創(chuàng)建導(dǎo)航欄按鈕
+ (UIBarButtonItem *)itemWithImageName:(NSString *)imageName highImageName:(NSString *)highImageName target:(id)target action:(SEL)action
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
[button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:highImageName] forState:UIControlStateHighlighted];
button.size = button.currentBackgroundImage.size;//按鈕的尺寸為按鈕的背景圖片的尺寸
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:button];
}
- 數(shù)組的安全操作
- (id)h_safeObjectAtIndex:(NSUInteger)index{
if(self.count == 0) {
NSLog(@"--- mutableArray have no objects ---");
return (nil);
}
if(index > MAX(self.count - 1, 0)) {
NSLog(@"--- index:%li out of mutableArray range ---", (long)index);
return (nil);
}
return ([self objectAtIndex:index]);
}
- 獲取當(dāng)前時間
-(NSDate *)getCurrentDate
{
NSDate *senddate = [NSDate date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *date1 = [dateformatter stringFromDate:senddate];
return [self stringToDate:date1 withDateFormat:@"YYYY-MM-dd HH:mm:ss"];
}
- 比較兩個時間的大小
-(int)compareDate:(NSDate*)date01 withDate:(NSDate*)date02{
int ci;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSComparisonResult result = [date01 compare:date02];
switch (result)
{
//date02比date01大
case NSOrderedAscending: ci=1; break;
//date02比date01小
case NSOrderedDescending: ci=-1; break;
//date02=date01
case NSOrderedSame: ci=0; break;
default: NSLog(@"erorr dates %@, %@", date01, date02); break;
}
return ci;
}
- 日期格式轉(zhuǎn)字符串
//日期格式轉(zhuǎn)字符串
- (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 3600]];
NSString *strDate = [dateFormatter stringFromDate:date];
return strDate;
}
- 字符串轉(zhuǎn)日期格式
- (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 3600]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *retdate = [dateFormatter dateFromString:dateString];
return retdate;
}
- 將世界時間轉(zhuǎn)化為中國區(qū)時間
- (NSDate *)worldTimeToChinaTime:(NSDate *)date
{
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSInteger interval = [timeZone secondsFromGMTForDate:date];
NSDate *localeDate = [date dateByAddingTimeInterval:interval];
return localeDate;
}
- 傳入今天的時間,返回明天的時間
//傳入今天的時間,返回明天的時間
- (NSString *)GetTomorrowDay:(NSDate *)aDate {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
[components setDay:([components day]+1)];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
[dateday setDateFormat:@"yyyy-MM-dd"];
return [dateday stringFromDate:beginningOfWeek];
}
- 字符串MD5加密
/** MD5加密得到sign字符串*/
+(NSString *) md5String:(NSString *) input {
const char *cStr = [input UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
- 字符串base64加密
+ (NSString *)base64StringFromText:(NSString *)text
{
if (text && ![text isEqualToString:LocalStr_None]) {
//取項目的bundleIdentifier作為KEY 改動了此處
//NSString *key = [[NSBundle mainBundle] bundleIdentifier];
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
//IOS 自帶DES加密 Begin 改動了此處
//data = [self DESEncrypt:data WithKey:key];
//IOS 自帶DES加密 End
return [self base64EncodedStringFrom:data];
}
else {
return LocalStr_None;
}
}
- base64解密字符串
/** 解密 */
+ (NSString *)textFromBase64String:(NSString *)base64
{
if (base64 && ![base64 isEqualToString:LocalStr_None]) {
//取項目的bundleIdentifier作為KEY 改動了此處
//NSString *key = [[NSBundle mainBundle] bundleIdentifier];
NSData *data = [self dataWithBase64EncodedString:base64];
//IOS 自帶DES解密 Begin 改動了此處
//data = [self DESDecrypt:data WithKey:key];
//IOS 自帶DES加密 End
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
else {
return LocalStr_None;
}
}
- 字符串反轉(zhuǎn)
**字符串反轉(zhuǎn)**
//第一種:
- (NSString *)reverseWordsInString:(NSString *)str
{
NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
for(NSInteger i = str.length - 1; i >= 0 ; i --)
{
unichar ch = [str characterAtIndex:i];
[newString appendFormat:@"%c", ch];
}
return newString;
}
- tableView刷新指定行
[tabelView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:IndexPath.row inSection:IndexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
- tableView刷新指定組
NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
- 將十六進制顏色轉(zhuǎn)換為 UIColor 對象
+ (UIColor *)colorWithHexString:(NSString *)color{
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// strip "0X" or "#" if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
- 全屏截圖
+ (UIImage *)shotScreen{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIGraphicsBeginImageContext(window.bounds.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- 截取view中某個區(qū)域生成一張圖片
+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
UIGraphicsBeginImageContext(scope.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
CGContextTranslateCTM(context, 0, rect.size.height);//下移
CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
CGContextDrawImage(context, rect, imageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(imageRef);
CGContextRelease(context);
return image;
}
- 給Image加圓角
給UIImage添加生成圓角圖片的擴展API:
- (UIImage *)imageWithCornerRadius:(CGFloat)radius {
CGRect rect = (CGRect){0.f, 0.f, self.size};
UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
//然后調(diào)用時就直接傳一個圓角來處理:
imgView.image = [[UIImage imageNamed:@"test"] hyb_imageWithCornerRadius:4];
//最直接的方法就是使用如下屬性設(shè)置:
imgView.layer.cornerRadius = 10;
// 這一行代碼是很消耗性能的
imgView.clipsToBounds = YES;
//好處是使用簡單,操作方便。壞處是離屏渲染(off-screen-rendering)需要消耗性能。對于圖片比較多的視圖上,不建議使用這種方法來設(shè)置圓角。通常來說,計算機系統(tǒng)中CPU、GPU、顯示器是協(xié)同工作的。CPU計算好顯示內(nèi)容提交到GPU,GPU渲染完成后將渲染結(jié)果放入幀緩沖區(qū)。
//簡單來說,離屏渲染,導(dǎo)致本該GPU干的活,結(jié)果交給了CPU來干,而CPU又不擅長GPU干的活,于是拖慢了UI層的FPS(數(shù)據(jù)幀率),并且離屏需要創(chuàng)建新的緩沖區(qū)和上下文切換,因此消耗較大的性能。
- 刪除緩存
- (void)removeCache
{
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",cachePath);
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
for (NSString *p in files) {
NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
}
}
- 計算清除的緩存大小
- (CGFloat)floatWithPath:(NSString *)path
{
CGFloat num = 0;
NSFileManager *man = [NSFileManager defaultManager];
if ([man fileExistsAtPath:path]) {
NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
NSString *fileName;
while ((fileName = [childFile nextObject]) != nil) {
NSString *fileSub = [path stringByAppendingPathComponent:fileName];
num += [self fileSizeAtPath:fileSub];
}
}
return num / (1024.0 * 1024.0);
}
- 計算單個文件大小
- (long long)fileSizeAtPath:(NSString *)file
{
NSFileManager *man = [NSFileManager defaultManager];
if ([man fileExistsAtPath:file]) {
return [[man attributesOfItemAtPath:file error:nil] fileSize];
}
return 0;
}
- 通過視圖,尋找父控制器
- (UIViewController *)viewController
{
for (UIView* next = [self superview]; next; next = next.superview) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
- 給textField加上右邊的視圖
UIButton *eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[eyeBtn setImage:[UIImage imageNamed:@"icon_close_eye"] forState:UIControlStateNormal];
[eyeBtn setImage:[UIImage imageNamed:@"icon_open_eye"] forState:UIControlStateSelected];
eyeBtn.width = 30;
eyeBtn.height = 30;
_passwordField.rightView = eyeBtn;
[eyeBtn addTarget:self action:@selector(showPwd:) forControlEvents:UIControlEventTouchUpInside];
_passwordField.rightViewMode = UITextFieldViewModeAlways;
- UITableViewCell選中后其子視圖顏色會改變,重寫下面兩個方法可以避免UI出入
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
[super setHighlighted:highlighted animated:animated];
self.lineview.backgroundColor = MColor;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
self.lineview.backgroundColor = MColor;
}
- 傳入一段H5代碼獲取其中所有的img元素的Url
- (NSArray *) getImageurlFromHtml:(NSString *) webString
{
NSMutableArray * imageurlArray = [NSMutableArray arrayWithCapacity:1];
//標(biāo)簽匹配
NSString *parten = @"<img(.*?)>";
NSError* error = NULL;
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
NSArray* match = [reg matchesInString:webString options:0 range:NSMakeRange(0, [webString length] - 1)];
for (NSTextCheckingResult * result in match) {
//過去數(shù)組中的標(biāo)簽
NSRange range = [result range];
NSString * subString = [webString substringWithRange:range];
//從圖片中的標(biāo)簽中提取ImageURL
NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
NSTextCheckingResult * subRes = match[0];
NSRange subRange = [subRes range];
subRange.length = subRange.length -1;
NSString * imagekUrl = [subString substringWithRange:subRange];
//將提取出的圖片URL添加到圖片數(shù)組中
[imageurlArray addObject:imagekUrl];
}
return imageurlArray;
}
- 給label加下劃線,中劃線
NSString *textStr = [NSString stringWithFormat:@"¥%@", oldPrice];
NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];
self.oldPrice_label.attributedText = attribtStr;
- 利用Quartz2D畫一張圖片保存到指定位置
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
CGContextStrokePath(ctx);
UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
NSData *data=UIImagePNGRepresentation(image);
[data writeToFile:@"/Users/yy-info/Documents/Practice/imgName.png" atomically:YES];
- 給UI控件加上虛線框(Quartz2D繪圖)
CGFloat width = _label.frame.size.width;
CGFloat height = _label.frame.size.height;
CAShapeLayer*shapelayer = [CAShapeLayer layer];
shapelayer.bounds=CGRectMake(0,0, width, height);
shapelayer.position=CGPointMake(CGRectGetMinX(_label.bounds),CGRectGetMinY(_label.bounds));
shapelayer.anchorPoint = CGPointMake(0, 0);
shapelayer.path= [UIBezierPath bezierPathWithRoundedRect:shapelayer.bounds cornerRadius:5].CGPath;
shapelayer.lineWidth = 1;
shapelayer.lineDashPattern=@[@5,@2];
shapelayer.fillColor=nil;
shapelayer.strokeColor= [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1].CGColor;
[_label.layer addSublayer:shapelayer];
*CALayer的震動
CAKeyframeAnimation*kfa = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
CGFloat s =16;
kfa.values=@[@(-s),@(0),@(s),@(0),@(-s),@(0),@(s),@(0)];
//時長
kfa.duration=.1f;
//重復(fù)
kfa.repeatCount=9;
//移除
kfa.removedOnCompletion=YES;
[_label.layer addAnimation:kfa forKey:@"shake"];