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

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...

Answers


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

Need Your Help

Why is rails not inserting data during create, only nil? (New scaffold)

ruby-on-rails commit null scaffold

I had an annoying problem with a freshly generated scaffold. Everything would run nicely, but while I could enter data, everytime I tried to save he would commit nil successfully. For all fields.

AngularJS, filters: how to turn a big giant object (JSON) into an array?

javascript arrays json angularjs

I'm having some issues with the Angular filters, according to the docs the filter only works with arrays, I have now a very big object, is actually to display some dynamic content. I will leave you...