Put border around partially transparent Image being drawn on CGContext
I have an image with a yellow vase in the foreground and transparent background:
I’m drawing it on a CGContext:
CGContextDrawImage(context, CGRectMake(0, 0, 100, 100), myImage.CGImage);
I can draw a shadow around it by using the following statement before
CGContextSetShadowWithColor(context, CGSizeMake(0,0), 5, [UIColor blueColor].CGColor);
But I want to put a stroke around the image, so that it’ll looks like following:
If I did this:
CGContextSetRGBStrokeColor(shadowContext, 0.0f, 0.0f, 1.0f, 1.0f); CGContextSetLineWidth(shadowContext, 5); CGContextStrokeRect(shadowContext, CGRectMake(0, 0, 100, 100));
It (obviously) draws a rectangular border around the whole iamge like this:
Which is not what I need.
But what’s the best way to draw the border as in the third image?
Please note that it’s not possible to use UIImageView in this case, so using the properties of CALayer of UIImageView is not applicable.
2 Solutions Collect From Internet About “Put border around partially transparent Image being drawn on CGContext”
One way to do this is to use the mathematical morphology operator of dilation to “grow” the alpha channel of the image outward, then use the resulting grayscale image as a mask to simulate a stroke. By filling the dilated mask, then drawing the main image on top, you get the effect of a stroke. I’ve created a demo showing this effect, available on Github here: https://github.com/warrenm/Morphology (all source is MIT licensed, should it prove useful to you).
And here’s a screenshot of it in action:
Note that this is staggeringly slow (dilation requires iteration of a kernel over every pixel), so you should pick a stroke width and precompute the mask image for each of your source images in advance.
I would try either setting the stroke color and line width before your call to
CGContextDrawImage, or tweaking the shadow (opacity, blur, etc) so that it looks like a stroke around the image. Let me know if this works!
- How to read/write from one IOS App set up with firebase, to another firebase database contained in another firebase project? Swift 3
- How to enable ARC for a single file
- Can I Animate an image iOS8 LaunchScreen.xib
- removeItemAtPath completion
- How to correct UIPopoverController is deprecated warning message?
- UIWebView not freeing all live bytes using ARC
- CGPointMake in Swift
- Decode a string in Swift
- Cannot print the FBSDKAccessToken.currentAccessToken().tokenString in my iOS9 app
- XCTestCase waitForExpectationsWithTimeout:handler: throwing EXC_BAD_ACCESS when expectation is not fulfilled
- Notify WatchKit app of an update without the watch app requesting it
- Create directory in app group container swift
- What exactly does removedOnCompletion = NO do?
- AVPlayer Lock Screen Controls
- How to properly handle a nil UIApplication.sharedApplication().keyWindow