assign a CAlayer to a UIImageView to be able to do

2019-06-09 07:24发布

Hi every one there is a link :link and there is a sample code in it where the author use a CALayer with CAShapeLayer.What I would like is to use this CALayer like it was a uiimageView (maybe assign to a uiimageview) to be able to move it etc...

1条回答
女痞
2楼-- · 2019-06-09 07:46

You cannot change the layer type of an existing UIView (meaning: you also can't change the layer of an UIImageView), but drawing to a layer is pretty easy: you need to assign a delegate to your CALayer, and that delegate needs to implement drawLayer:inContext:.

Another solution might be to create a UIView subclass and implement +layerClass:

+ (Class)layerClass
{
    return [CAShapeLayer class];
}

That way your view will use a shape layer and you might be able to simply use the usual UIView's drawRect: method. You could then access the layer via (CAShapeLayer *)[self layer] to modify it. I haven't tried this approach, though.

Edit: Explaining how the second solution would be done:

@interface MyView : UIView {
    UIImage *image;
}
@property(retain) UIImage *image;
@end


@implementation MyView
@synthesize image;

+ (Class)layerClass
{
    return [CAShapeLayer class];
}

- (void)dealloc
{
    self.image = nil;
    [super dealloc];
}

- (void)drawRect:(CGRect)rect
{
    // Draw the image. You might need to play around with this,
    // for example to draw the image as aspect fit or aspect fill.
    [image drawInRect:rect];
}
@end
查看更多
登录 后发表回答