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

时间: 2024-11-05 18:57:31

iOS计算字符串的宽度高度的相关文章

【代码笔记】获取字符串的宽度,高度

一,代码. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //获取字符串的宽度 NSLog(@"获得字符串的宽度:%f",[self widthForString:@"我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!我爱你!" fontSize:10.0 andHeight:

java计算字符串的宽度和高度

//g对象为一个GraphicsFontMetrics fm = g.getFontMetrics ():          int strWidth = fm.stringWidth ("Registering plug-ins……"):          int strHeight = fm.getHeight (): 转载:http://sbje5201314.blog.163.com/blog/static/280338620086332426488/

iOS: 计算 UIWebView 的内容高度

- (void)webViewDidFinishLoad:(UIWebView *)wb { //方法1 CGFloat documentWidth = [[wb stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').offsetWidth"] floatValue]; CGFloat documentHeight = [[wb stringByEvaluatingJavaScriptFr

iOS根据字符串计算UITextView高度

iOS计算字符串高度,有需要的朋友可以参考下. 方法一:ios7.0之前适用 /** @method 获取指定宽度width,字体大小fontSize,字符串value的高度 @param value 待计算的字符串 @param fontSize 字体的大小 @param Width 限制字符串显示区域的宽度 @result float 返回的高度 */ - (float) heightForString:(NSString *)value fontSize:(float)fontSize a

iOS依据字符串计算UITextView高度

iOS计算字符串高度,有须要的朋友能够參考下. 方法一:ios7.0之前适用 /** @method 获取指定宽度width,字体大小fontSize,字符串value的高度 @param value 待计算的字符串 @param fontSize 字体的大小 @param Width 限制字符串显示区域的宽度 @result float 返回的高度 */ - (float) heightForString:(NSString *)value fontSize:(float)fontSize a

关于UIFont和计算字符串的高度和宽度

转自:http://i.cnblogs.com/EditPosts.aspx?opt=1 1.创建方法:+ fontWithName:size:- fontWithSize:2.创建系统字体:+ systemFontOfSize:+ boldSystemFontOfSize:+ italicSystemFontOfSize:3.获得可用的Font Names:+ familyNames+ fontNamesForFamilyName:4.获得Font Name属性:familyName 属性 和

计算字符串高度宽度

//计算字符串宽度: + (CGFloat)width:(NSString *)contentString heightOfFatherView:(CGFloat)height textFont:(UIFont *)font{ #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0 CGSize size = [contentString sizeWithFont:font constrainedToSize:CGSizeMake(CGFLOAT_

iOS 7 计算字符串高度

- (float)width:(NSString *)str font:(UIFont *)font { NSDictionary *attribute = @{NSFontAttributeName:font}; CGSize size = [str boundingRectWithSize:CGSizeMake(_bgView.frame.size.width - 2*MARGIN_TOP, CGFLOAT_MAX) options: NSStringDrawingTruncatesLast

iOS 字符串的宽度和高度自适应

//获取字符串的宽度 -(float)widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height { UIColor *backgroundColor=[UIColor blackColor]; UIFont *font=[UIFont boldSystemFontOfSize:fontSize]; CGRect sizeToFit = [value boundingRectWithSize: