CALayer中坐标是以几何坐标为标准的
按照例子来进行调整吧
#import "RoundAndShadowViewController.h"
#define PHOTO_HEIGHT 150
@interface RoundAndShadowViewController () {
int method;
}
@end
@implementation RoundAndShadowViewController
/**
当使用masksToBounds=YES的时候,再添加一个图层,只作为阴影使用,就可以解决这个问题
*/
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
/**
method:
1:当为1的时候用CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -PHOTO_HEIGHT);解决倒置
2:transform解决图片倒置问题
3:直接赋值contents对图片直接赋值
*/
method = 1;
CGPoint position = CGPointMake(160, 200);
CGRect bounds = CGRectMake(0, 0, PHOTO_HEIGHT, PHOTO_HEIGHT);
CGFloat cornerRadius = PHOTO_HEIGHT/2;
CGFloat borderWith = 2;
//阴影图层
CALayer *layerShadow = [[CALayer alloc] init];
layerShadow.bounds = bounds;
layerShadow.position = position;
layerShadow.cornerRadius = cornerRadius;
layerShadow.shadowColor = [UIColor grayColor].CGColor;
layerShadow.shadowOffset = CGSizeMake(2, 1);
layerShadow.shadowOpacity = 1;
layerShadow.borderWidth = borderWith;
layerShadow.borderColor = [UIColor whiteColor].CGColor;
[self.view.layer addSublayer:layerShadow];
//容器图层
CALayer *layer = [[CALayer alloc] init];
layer.bounds = bounds;
layer.position = position;
layer.backgroundColor = [UIColor redColor].CGColor;
layer.cornerRadius = cornerRadius;
layer.masksToBounds = YES;
layer.borderColor = [UIColor whiteColor].CGColor;
layer.borderWidth = borderWith;
#pragma mark 利用图层形变解决图像倒立问题
if (method == 2) {
/**
直接利用CATransform3D类型的transform来解决图形的倒立问题
*/
layer.transform = CATransform3DMakeRotation(M_PI, 1, 0, 0);
}
if (method == 3) {
#pragma mark 事实上,如果只是添加一张图片,就没必要这么麻烦了,直接设置contexts即可,不涉及倒立问题
UIImage *image = [UIImage imageNamed:@"test"];
[layer setContents:(id)image.CGImage];
}
if (method == 2||method == 1) {
//设置图层代理
layer.delegate = self;
//调用图层setNeedDisplay,否则代理方法不会被调用
[layer setNeedsDisplay];
}
//添加图层到跟图层
[self.view.layer addSublayer:layer];
}
#pragma mark 绘制图形、图像到图层
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
if (method == 1) {
//不用transform解决
CGContextSaveGState(ctx);
//图形上下文形变
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -PHOTO_HEIGHT);
UIImage *image = [UIImage imageNamed:@"test"];
//注意这个位置是相对于图层而言的不是屏幕
CGContextDrawImage(ctx, CGRectMake(0, 0, PHOTO_HEIGHT, PHOTO_HEIGHT), image.CGImage);
CGContextRestoreGState(ctx);
} else if (method == 2) {
#pragma mark 利用transform解决倒立问题
UIImage *image = [UIImage imageNamed:@"test"];
CGContextDrawImage(ctx, CGRectMake(0, 0, PHOTO_HEIGHT, PHOTO_HEIGHT), image.CGImage);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end