assign a CAlayer to a UIImageView to be able to do all you can do with a UIImageView

情到浓时终转凉″ 提交于 2019-12-08 10:45: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:


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


来源:https://stackoverflow.com/questions/8325492/assign-a-calayer-to-a-uiimageview-to-be-able-to-do-all-you-can-do-with-a-uiimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!