你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 生成隨機顏色(UIColor)

iOS 生成隨機顏色(UIColor)

編輯:IOS開發綜合


#import


@interface UIColor (RandomColor)

+(UIColor *) randomColor;

@end



#import "UIColor+RandomColor.h"


@implementation UIColor (RandomColor)


+(UIColor *) randomColor

{

CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0

CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white

CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black

return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

@end



將隨機生成的顏色繪制成圖片。


-(void)createImage

{


NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];


path = @"/Users/shouqiangwei/Desktop/未命名文件夾 2";

NSLog(@"path = %@",path);

NSString *imgName;

NSString *imgURL;

NSString *markNum;

UIImage *img;

NSData *imgData;

NSError *err;

int width= 1000, height=1000, fontSize;

CGPoint markPoint;

int baseLength = 320;

NSFileManager *fm = [NSFileManagerdefaultManager];

for (int i=0; i<1000; i++) {


UIColor *color = [UIColorrandomColor];

[_currentColorImageViewsetBackgroundColor:color];


imgName = [NSString stringWithFormat:@"%i.jpg", i+1];

_lblCount.text = imgName;


imgURL = [path stringByAppendingPathComponent:imgName];

if (![fm fileExistsAtPath:imgURL]) {

const CGFloat *colorComps = CGColorGetComponents(color.CGColor);

markNum = [NSString stringWithFormat:@"%i", i+1];


fontSize = width / 5;

markPoint = CGPointMake(fontSize/2, fontSize/2);


UIGraphicsBeginImageContext(CGSizeMake(width, height));

CGContextRef ctx =UIGraphicsGetCurrentContext();

CGContextSetRGBFillColor(ctx, colorComps[0], colorComps[1], colorComps[2], colorComps[3]);

CGContextFillRect(ctx, CGRectMake(0, 0, width, height));

CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0,1.0);


//創建圖片上的數字。

[markNum drawAtPoint:markPoint withFont:[UIFont systemFontOfSize:fontSize]];

img = UIGraphicsGetImageFromCurrentImageContext();

self.imageView.image= img;

UIGraphicsEndImageContext();



//創建到本地。

imgData = [NSDatadataWithData:UIImageJPEGRepresentation(img,1.0f)];


[imgData writeToFile:imgURLoptions:NSDataWritingAtomicerror:&err];


if (err) {

NSLog(@"error: %@\nimage:%@", err.localizedDescription, imgName);

} else {

NSLog(@"done: %@", imgName);

}

}

}


}




  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved