1.全屏图片设置
大致思路是判断屏幕高度来选择不同图片,用一个分类封装起来直接调用
typedef NS_ENUM(NSInteger, thisDeviceClass) {
thisDeviceClass_iPhone5,
thisDeviceClass_iPhone6,
thisDeviceClass_iPhone6plus,
thisDeviceClass_iPhoneX,
thisDeviceClass_unknown
};
thisDeviceClass currentDeviceClass();
@interface UIImage (DeviceSpecificMedia)
+ (instancetype )imageForDeviceWithName:(NSString *)fileName;
@end
#import "UIImage+DeviceSpecificMedia.h"
thisDeviceClass currentDeviceClass() {
CGFloat greaterPixelDimension = (CGFloat) fmaxf(((float)[[UIScreen mainScreen]bounds].size.height),
((float)[[UIScreen mainScreen]bounds].size.width));
switch ((NSInteger)greaterPixelDimension) {
case 568:
return thisDeviceClass_iPhone5;
break;
case 667:
return thisDeviceClass_iPhone6;
break;
case 736:
return thisDeviceClass_iPhone6plus;
break;
case 812:
return thisDeviceClass_iPhoneX;
break;
default:
return thisDeviceClass_unknown;
break;
}
}
@implementation UIImage (DeviceSpecificMedia)
+ (NSString *)magicSuffixForDevice
{
switch (currentDeviceClass()) {
case thisDeviceClass_iPhone5:
return @"-568h";
break;
case thisDeviceClass_iPhone6:
return @"-667h"; //or some other arbitrary string..
break;
case thisDeviceClass_iPhone6plus:
return @"-736h";
break;
case thisDeviceClass_iPhoneX:
return @"-812h";
break;
case thisDeviceClass_unknown:
default:
return @"";
break;
}
}
+ (instancetype )imageForDeviceWithName:(NSString *)fileName
{
UIImage *result = nil;
NSString *nameWithSuffix = [fileName stringByAppendingString:[UIImage magicSuffixForDevice]];
result = [UIImage imageNamed:nameWithSuffix];
if (!result) {
result = [UIImage imageNamed:fileName];
}
return result;
}
@end
2.渐变色图片生成
首先用CAGradientLayer生成渐变的图层:
+ (CAGradientLayer *)layerFromStartColor:(UIColor *)startColor stopColor:(UIColor *)stopColor frame:(CGRect)frame
{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)startColor.CGColor,(__bridge id)stopColor.CGColor];
gradientLayer.locations = @[@0.0,@1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = frame;
return gradientLayer;
}
这里我简化了一下,因为一般只用简单的首尾两种颜色渐变,当然可以设置多种颜色。
然后将图层(CALayer)转换成图片(UIImage)
+ (UIImage *)imageFromLayer:(CALayer *)layer
{
UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}