iOS計算字符串的寬度高度


OC開發中會遇到根據字符串和字體大小來算計算出字符串所占的寬高->> 封裝方法如下:

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

 

@interface XSDKResourceUtil : NSObject

//獲取字符串寬

+(CGSize)measureSinglelineStringSize:(NSString*)str andFont:(UIFont*)wordFont;

//獲取字符串寬 // 傳一個字符串和字體大小來返回一個字符串所占的寬度

+(float)measureSinglelineStringWidth:(NSString*)str andFont:(UIFont*)wordFont;

//獲取字符串高 // 傳一個字符串和字體大小來返回一個字符串所占的高度

+(float)measureMutilineStringHeight:(NSString*)str andFont:(UIFont*)wordFont andWidthSetup:(float)width;

 

+(UIImage*)imageAt:(NSString*)imgNamePath;

 

+(BOOL)xsdkcheckName:(NSString*)name;

+(BOOL)xsdkcheckPhone:(NSString *)userphone;

 

+ (UIColor *)xsdkcolorWithHexString:(NSString *)color alpha:(CGFloat)alpha;

 

+(BOOL)xsdkstringIsnilOrEmpty:(NSString*)string;

 

+(BOOL)jsonFieldIsNull:(id)jsonField;

+(int)filterIntValue:(id)value withDefaultValue:(int)defaultValue;

+(NSString*)filterStringValue:(id)value withDefaultValue:(NSString*)defaultValue;

@end

 

// -------------------------------------方法具體實現-------------------------------------------

#import "XSDKResourceUtil.h"

 

@implementation XSDKResourceUtil

+(float)measureMutilineStringHeight:(NSString*)str andFont:(UIFont*)wordFont andWidthSetup:(float)width{

    if (str == nil || width <= 0) return 0;

    CGSize measureSize;

    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){

        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

    }else{

        measureSize = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;

    }

    return ceil(measureSize.height);

}

// 傳一個字符串和字體大小來返回一個字符串所占的寬度

+(float)measureSinglelineStringWidth:(NSString*)str andFont:(UIFont*)wordFont{

    if (str == nil) return 0;

    CGSize measureSize;

    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){

        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

    }else{

        measureSize = [str boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;

    }

    return ceil(measureSize.width);

}

 

+(CGSize)measureSinglelineStringSize:(NSString*)str andFont:(UIFont*)wordFont

{

    if (str == nil) return CGSizeZero;

    CGSize measureSize;

    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){

        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

    }else{

        measureSize = [str boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;

    }

    return measureSize;

}

 

//+(UIImage*)imageAt:(NSString*)imgNamePath{

//    if (imgNamePath == nil || [[imgNamePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0) {

//        return nil;

//    }

//    return [UIImage imageNamed:[ImageResourceBundleName stringByAppendingPathComponent:imgNamePath]];

//}

 

+(BOOL)xsdkcheckName:(NSString*)name{

    if([XSDKResourceUtil xsdkstringIsnilOrEmpty:name]){

        return NO;

    }else{

        if(name.length < 5){

            return NO;

        }

        

        if(name.length > 20){

            return NO;

        }

        

        NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[a-zA-Z][a-zA-Z0-9_]*$"];

        if(![pred evaluateWithObject:name]){

            return [XSDKResourceUtil xsdkcheckPhone:name];

        }

    }

    return YES;

}

 

+(BOOL)xsdkcheckPhone:(NSString *)userphone

{

    NSPredicate * phone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^1\\d{10}"];

    if (![phone evaluateWithObject:userphone]) {

        return NO;

    }

    return YES;

}

 

+(BOOL)xsdkstringIsnilOrEmpty:(NSString*)string{

    if (string == nil || [string isKindOfClass:[NSNull class]]  || [string isEqualToString:@""]) {

        return YES;

    }else{

        return NO;

    }

}

 

+(UIColor *)xsdkcolorWithHexString:(NSString *)color alpha:(CGFloat)alpha

{

    //刪除字符串中的空格

    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters

    if ([cString length] < 6)

    {

        return [UIColor clearColor];

    }

    // strip 0X if it appears

    //如果是0x開頭的,那么截取字符串,字符串從索引為2的位置開始,一直到末尾

    if ([cString hasPrefix:@"0X"])

    {

        cString = [cString substringFromIndex:2];

    }

    //如果是#開頭的,那么截取字符串,字符串從索引為1的位置開始,一直到末尾

    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:alpha];

}

 

+(BOOL)jsonFieldIsNull:(id)jsonField{

    return (jsonField == nil || [jsonField isKindOfClass:[NSNull class]]);

}

 

+(int)filterIntValue:(id)value withDefaultValue:(int)defaultValue{

    if (![XSDKResourceUtil jsonFieldIsNull:value]) {

        return [value intValue];

    }else{

        return defaultValue;

    }

}

 

+(NSString*)filterStringValue:(id)value withDefaultValue:(NSString*)defaultValue{

    if ([value isKindOfClass:[NSString class]] && ![XSDKResourceUtil xsdkstringIsnilOrEmpty:value]) {

        return value;

    }else{

        return defaultValue;

    }

}

@end

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM