【问题标题】:Return a random image in iOS在 iOS 中返回随机图像
【发布时间】:2012-09-02 04:30:23
【问题描述】:

我的 Xcode 项目中有 6 个 .png 图像(例如:image1.png、image2.png 等)。我想创建一个方法,从这组 6 个中返回一个随机图像并将其分配给我的视图背景。我已经有一个返回随机颜色的类似方法:

+(UIColor *)randomColor
{
CGFloat red= (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue= (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green= (CGFloat)random()/(CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];

} 

我的实现文件这样调用这个方法:

UIColor *randomColor=[SoundDetail randomColor];
[self.view setBackgroundColor:randomColor];

如何编辑此方法以从我的 6 个列表中返回随机图像并将其分配给我的背景视图? 我将 Xcode 4.4.1 用于通用 iOS 5 项目。

谢谢!

【问题讨论】:

  • arc4random_uniform 优于 rand 或 random,仅供参考

标签: iphone objective-c ios xcode


【解决方案1】:
UIImage * randomImage = [ UIImage imageNamed:[ NSString stringWithFormat:@"image%u.png", 1+arc4random_uniform(6) ] ] ;

【讨论】:

  • (假设你的图片是 image1.png...image7.png)
【解决方案2】:

假设你在一个 NSArray 中有 UIImages:

- (UIImage *)randomImage
{
    NSArray *imagesArray = // array of images;
    return [imagesArray objectAtIndex:(arc4random() % imagesArray.count];
}

假设您在 NSArray 中有 UIImage 名称:

- (UIImage *)randomImage
{
    NSArray *imagesArray = // array of image names;
    NSString *imageName = [imagesArray objectAtIndex:(arc4random() % imagesArray.count];
    return [UIImage imageNamed:imageName];
}

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    相关资源
    最近更新 更多