How to set cornerRadius to UIImage inside a Button? - ios

I am creating Image with gradient, and i want the button to have cornerRadius
button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.frame = CGRectMake(self.view.frame.size.width/2 - button.frame.size.width, 100, 250, 50)
button.layer.cornerRadius = 3
button.setTitle("ViewThree", forState: UIControlState.Normal)
button.addTarget(self, action: "ViewControllerAction:", forControlEvents: UIControlEvents.TouchUpInside)
button.setBackgroundImage(getImageWithGradient(UIColor(netHex:0x2d72cf).CGColor, bottom: UIColor(netHex:0x2d72cf).CGColor, size: CGSize(width: button.bounds.width, height: button.bounds.height), frame: button.bounds), forState: UIControlState.Normal)
func getImageWithGradient(top: CGColor, bottom: CGColor, size: CGSize, frame: CGRect) -> UIImage{
var image = UIImage()
UIGraphicsBeginImageContext(frame.size)
var context = UIGraphicsGetCurrentContext()
image.drawAtPoint(CGPointMake(0, 0))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let locations:[CGFloat] = [0.0, 1.0]
let gradient = CGGradientCreateWithColors(colorSpace,
[top, bottom], locations)
let startPoint = CGPointMake(frame.size.width / 2, 0)
let endPoint = CGPointMake(frame.size.width / 2, frame.size.height)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
but no matter what i try there is no corner radius, how should i try this

Try setting the UIButton's clipToBounds property to YES

Go to your story board and click on the button. Go to this buttons identity inspector and "User Defined Runtime Attributes" for Key Path "layer.cornerRadius" for Type "Number" for Value "10" i like to use 10 but you can play around with it! If you are doing this in code, under your line
button.layer.cornerRadius = 3
add the line
button.layer.masksToBounds = true

Related

Swift - How to make UIButton tap Interaction only on the image attached and ignore transparent parts

I am creating buttons with different image shapes... Everything is working but if for example, a diamond shape is created, you can click on the transparent part of the button. I managed to set up the shadow to respect the shape of the button so it looks highlighted but how do I apply this so the transparent part of the buttons is ignored when interacted with?
I found some answers but I do not use paths to create the UIButton shape but an image on the UIButton.
Below is how to create one of my buttons and set the glow
extension UIbutton {
func createSquareButton(buttonPositionX: CGFloat, buttonPositionY: CGFloat, buttonWidth: CGFloat, buttonHeight: CGFloat, buttonTitle: String) {
let button = self
button.isUserInteractionEnabled = true
button.frame = CGRect(x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.setTitleColor(UIColor.black, for: .highlighted)
button.alpha = 1.0
button.titleLabel?.font = .systemFont(ofSize: 20)
button.backgroundColor = nil
button.tintColor = Style.PurpleColor
let image = UIImage(named: "Plain Square")
let imageView = UIImageView(image: image)
imageView.setImageColor(color: Style.PurpleColor)
button.setBackgroundImage(imageView.image, for: .normal)
button.setBackgroundImage(imageView.image, for: .selected)
button.setBackgroundImage(imageView.image, for: .highlighted)
}
}
func buttonGlow(sender: CustomBtn){
for button in buttonArray {
if button.UUIDtag == currentSelectedMarkerUUID {
sender.layer.shadowColor = button.tintColor.cgColor
sender.layer.shadowRadius = 15
sender.layer.shadowOpacity = 1.0
sender.layer.masksToBounds = false
} else {
let otherBtn = tmpButtonPicked(uuid: button.UUIDtag!)
otherBtn.layer.shadowColor = UIColor.clear.cgColor
otherBtn.layer.shadowRadius = 0
}
}
}
extension UIImageView {
func setImageColor(color: UIColor) {
let templateImage = self.image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
Thanks to Malik's help I solved the problem.
Firstly you need to implement the function below which recognizes what is the alpha value where you tap within the button.
func alphaFromPoint(sender: CustomBtn, point: CGPoint) -> CGFloat {
var pixel: [UInt8] = [0, 0, 0, 0]
let colourSpace = CGColorSpaceCreateDeviceRGB()
let alphaInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colourSpace, bitmapInfo: alphaInfo.rawValue)
context?.translateBy(x: -point.x, y: -point.y)
sender.layer.render(in: context!)
let floatAlpha = CGFloat(pixel[3])
return floatAlpha
}
then I tweaked #IBaction to also receive the type of event. I then Added the code Malik mentioned to the #IBaction
#IBAction func mainButton(sender: CustomBtn, forEvent event: UIEvent){
let touches = event.touches(for: sender)
let touch = touches?.first
guard let touchPoint = touch?.location(in: sender) else {return}
let alphaValue = alphaFromPoint(sender: sender, point: touchPoint)
if alphaValue > 0 {
//Do Something if the alpha value is bigger than 0
}
}
If the value returned from the alphaValue variable is 0 then you know its transparent.
Swift 5 version alphaFromPoint function.
func alphaFromPoint(point: CGPoint) -> CGFloat
{
var pixel: [UInt8] = [0, 0, 0, 0]
let colorSpace = CGColorSpaceCreateDeviceRGB();
let alphaInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: alphaInfo.rawValue)
context!.translateBy(x: -point.x, y: -point.y);
self.layer.render(in: context!)
let floatAlpha = CGFloat(pixel[3])
return floatAlpha
}

UISegmentedControl TintColor to Gradient Color

I am trying to set UIsegmentedControl tint color for the selected segment to gradient color and I am unable to do it
I am trying to follow this article https://www.bethedev.com/2019/02/set-gradient-tint-color-for-segmented.html
Trying to use this code:
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white],for: UIControl.State.normal)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white],for: UIControl.State.selected)
fileprivate func updateGradientBackground() {
let sortedViews = segmentedControl.subviews.sorted( by: { $0.frame.origin.x < $1.frame.origin.x } )
for (_, view) in sortedViews.enumerated() {
// let gradientImage = gradient(size: segmentedControl.frame.size, color: [UIColor.cyan,UIColor.blue])!
view.backgroundColor = UIColor(patternImage: UIImage(named: "segmentedRectangle.png")!)
view.tintColor = UIColor.clear
}
}
I am expecting only one segment to be of the segmentedRectangle.png image color but it is displaying on the entire segmented control like this.
Try this code, I put comments on relevant parts. Let me know if you need more explanation.
let segmentedControl: UISegmentedControl = {
let view = UISegmentedControl(items: ["Pounds", "Kilograms"])
view.selectedSegmentIndex = 0
view.tintColor = .black
view.backgroundColor = .white
view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40, height: 20)
/// Gradient
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40, height: 20)
let leftColor = UIColor.red
let rightColor = UIColor.purple
gradient.colors = [leftColor.cgColor, rightColor.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
/// Create gradient image
UIGraphicsBeginImageContext(gradient.frame.size)
gradient.render(in: UIGraphicsGetCurrentContext()!)
let segmentedControlImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Normal Image
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size);
let context:CGContext = UIGraphicsGetCurrentContext()!;
context.setFillColor(UIColor.white.cgColor)
context.fill(rect)
let normalImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
/// Set segmentedControl image
view.setBackgroundImage(normalImage, for: .normal, barMetrics: .default)
view.setBackgroundImage(segmentedControlImage, for: .selected, barMetrics: .default)
return view
}()
Usage:
On your ViewDidLoad set navigationItem title view as your segmented control like so:-
self.navigationItem.titleView = segmentedControl
I think with few modifications/custominization you can get want you want, Cheers :)
StoryBoard/InterfaceBuilder
Just call this inside your ViewDidLoad and pass your outlet name on the function call: -
func configureSegementedControl(segmentedControl: UISegmentedControl) {
segmentedControl.selectedSegmentIndex = 0
segmentedControl.tintColor = .black
segmentedControl.backgroundColor = .white
segmentedControl.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40, height: 20)
/// Gradient
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 40, height: 20)
let leftColor = UIColor.red
let rightColor = UIColor.purple
gradient.colors = [leftColor.cgColor, rightColor.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
/// Create gradient image
UIGraphicsBeginImageContext(gradient.frame.size)
gradient.render(in: UIGraphicsGetCurrentContext()!)
let segmentedControlImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Normal Image
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size);
let context:CGContext = UIGraphicsGetCurrentContext()!;
context.setFillColor(UIColor.white.cgColor)
context.fill(rect)
let normalImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
/// Set segmentedControl image
segmentedControl.setBackgroundImage(normalImage, for: .normal, barMetrics: .default)
segmentedControl.setBackgroundImage(segmentedControlImage, for: .selected, barMetrics: .default)
}

Draw border of certain color around colored UIImage in tab bar

In order to understand my problem I will start with a short description of my goal:
In the center of my tab bar I deliberately use a usually too big image (a circle) which extends over the tab bar (the tab bar's background color is white) so it laps over the top border of the tab bar. Since all UITabBarItems' default color is a light gray (apparently it is neither UIColor.lightGray nor .darkGray) and I would like to change the color of this (and only this) UITabBarItem (or rather the image considering this is the only thing which can be seen of this UITabBarItem) to white I've used the following extension/function which works fine:
extension UIImage {
func tabBarImageWithCustomTint(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode(rawValue: 1)!)
let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
newImage = newImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return newImage
}
}
Link to question where I found this extension
As both the tint color of the image and the background color of the tab bar are white, I would now like to add a border of red color to the now white image. Luckily, I managed to find another question on stackoverflow which answered this question (although I must add that I am not entirely content with this extension because it leaves a very small space between the UIImage and the border):
extension UIImage {
func roundedImageWithBorder(width: CGFloat, color: UIColor) -> UIImage? {
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
My problem now is if I use the function consecutively like this...:
let tabRecordButton = UIImage(named: "circle").tabBarImageWithCustomTint(tintColor: .white).roundedImageWithBorder(width: 1, color: .red)
..., the border is drawn but the UITabBarItem's tint color goes back to this default gray aforementioned (not even the border is red).
So my question: Is there a way I can do both, i.e. color the image white and the border red in my UITabBar?
You have to add this line result = result.withRenderingMode(UIImageRenderingMode.alwaysOriginal) in your second extension as well, if you omit this line then your image will take the tint from your tabBar, that is your original issue
replace your roundedImageWithBorder extension method implementation with this one
func roundedImageWithBorder(width: CGFloat, color: UIColor) -> UIImage? {
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
var result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
result = result?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return result
}
Testing
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tabBarItem.selectedImage = UIImage(named: "icono-menu")?.tabBarImageWithCustomTint(tintColor: UIColor.magenta).roundedImageWithBorder(width: 1, color: UIColor.blue)
self.tabBarController?.tabBar.tintColor = UIColor.red //note that the tintColor of the tabBar is red
}
Result

How to set circle button with background image on right navigation bar item

I have tried to put circle button on right navigation bar of iOS but unfortunately When I use button background it doesn't round the image it shows square shape background image but When I remove image and put background colour it round the button with background colour.
Code that I tried:
let button = UIButton()
button.frame = CGRectMake(0, 0, 40, 40)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.setImage(self.myPic, forState: .Normal)
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
Try to use this code..
for rounded button with image -
let button = UIButton()
button.frame = CGRectMake(0, 0, 40, 40)
let color = UIColor(patternImage: UIImage(named: "btnImage")!)
button.backgroundColor = color
button.layer.cornerRadius = 0.5 * button.bounds.size.width
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
With Actual image---
let button = UIButton()
button.frame = CGRectMake(0, 0, 40, 40)
let image = UIImage(named: "btnImage")!
UIGraphicsBeginImageContextWithOptions(button.frame.size, false, image.scale)
let rect = CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)
UIBezierPath(roundedRect: rect, cornerRadius: rect.width/2).addClip()
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let color = UIColor(patternImage: newImage)
button.backgroundColor = color
button.layer.cornerRadius = 0.5 * button.bounds.size.width
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
I made a solution for Swift 4, you need to resize the image and the frame too
let avatarSize: CGFloat = 30
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: avatarSize, height: avatarSize)
button.setImage(UIImage(named: "avatar")?.resizeImage(avatarSize, opaque: false), for: .normal)
if let buttonImageView = button.imageView {
button.imageView?.layer.cornerRadius = buttonImageView.frame.size.width / 2
button.imageView?.clipsToBounds = true
button.imageView?.contentMode = .scaleAspectFit
}
Extension you need:
extension UIImage {
func resizeImage(_ dimension: CGFloat, opaque: Bool, contentMode:
UIViewContentMode = .scaleAspectFit) -> UIImage {
var width: CGFloat
var height: CGFloat
var newImage: UIImage
let size = self.size
let aspectRatio = size.width/size.height
switch contentMode {
case .scaleAspectFit:
if aspectRatio > 1 { // Landscape image
width = dimension
height = dimension / aspectRatio
} else { // Portrait image
height = dimension
width = dimension * aspectRatio
}
default:
fatalError("UIIMage.resizeToFit(): FATAL: Unimplemented ContentMode")
}
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = opaque
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
newImage = renderer.image {
(context) in
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
}
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
}
swift 2
set bar button in circle
func setProfileImageOnBarButton() {
let button = UIButton()
button.setImage(profileImage, forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.openUserProfile), forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 36, 36)
button.layer.cornerRadius = CGRectGetWidth(button.frame) / 2
button.layer.masksToBounds = true
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
}
Swift 5 - You can simply do that, and make sure you make clipstobounds to true
teacherImage.setImage(UIImage(named: "icon_profile"), for: .normal)
teacherImage.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
teacherImage.addTarget(self, action: #selector(addPressed), for: .touchUpInside)
teacherImage.layer.cornerRadius = 0.5 * teacherImage.bounds.size.width
teacherImage.clipsToBounds = true
let rightNavBarButton = UIBarButtonItem(customView: teacherImage)
let currWidth = rightNavBarButton.customView?.widthAnchor.constraint(equalToConstant: 40)
currWidth?.isActive = true
let currHeight = rightNavBarButton.customView?.heightAnchor.constraint(equalToConstant: 40)
currHeight?.isActive = true
self.navigationItem.rightBarButtonItem = rightNavBarButton
It works for Objective-C. Have a try!
UIButton *avatarButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
// redraw the image to fit new size
UIGraphicsBeginImageContextWithOptions(avatarButton.frame.size, NO, 0);
[[UIImage imageNamed:#"pikachu"] drawInRect:CGRectMake(0, 0, avatarButton.frame.size.width, avatarButton.frame.size.height)];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIColor *color = [UIColor colorWithPatternImage: resultImage];
avatarButton.backgroundColor = color;
avatarButton.layer.cornerRadius = 0.5 * avatarButton.bounds.size.width;
UIBarButtonItem *barButton = UIBarButtonItem.new;
barButton.customView = avatarButton;
self.navigationItem.rightBarButtonItem = barButton;

Center UIButton text for floating action button like Inbox app

floatingButton = UIButton(x: blocx, y:blocy, width: imageSize, height: imageSize, target: self, action: "clickedFloatingButton")
floatingButton!.backgroundColor = CozyColors.StatCardSkip
floatingButton!.layer.cornerRadius = floatingButton!.frame.size.width / 2
floatingButton!.setTitle("+", forState: UIControlState.Normal)
floatingButton!.setTitleColor(CozyColors.ThemeWhite, forState: UIControlState.Normal)
floatingButton!.titleLabel?.font = UIFont(name: CozyStyles.ThemeFontName, size: imageSize*2/3)
view.addSubview(floatingButton!)
Here is the result:
As you can see the plus button is not aligned properly to the center. How can I put it right in the middle without adding a UILabel as a subview?
Try this code :
var floatingButton = UIButton(frame: CGRectMake(10, 20, 50, 50))
floatingButton.backgroundColor = UIColor.redColor()
floatingButton.layer.cornerRadius = floatingButton.frame.size.width / 2
floatingButton.setTitle("+", forState: UIControlState.Normal)
floatingButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
floatingButton.titleLabel?.font = UIFont(name: floatingButton.titleLabel!.font.familyName , size: 50)
floatingButton.titleEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, 0)
view.addSubview(floatingButton)
Well,I think a easier way is just set a background image for it
floatingButton.setBackgroundImage(UIImage(named: "icon.png"), forState: UIControlState.Normal)
You can apply the transform or find a similar image from google
And the background image is here
You set your Title Edge Inset as below. Change its value and set title middle.
floatingButton.titleEdgeInsets = UIEdgeInsetsMake(-24, 0, 0, 0);
according below function change value.
func UIEdgeInsetsMake(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> UIEdgeInsets
You can simply draw your button with UIBezierPath and here is your code:
import UIKit
class PushButtonView: UIButton {
override func drawRect(rect: CGRect) {
var path = UIBezierPath(ovalInRect: rect)
UIColor.redColor().setFill()
path.fill()
//set up the width and height variables
//for the horizontal stroke
let plusHeight: CGFloat = 3.0
let plusWidth: CGFloat = min(bounds.width, bounds.height) * 0.6
//create the path
var plusPath = UIBezierPath()
//set the path's line width to the height of the stroke
plusPath.lineWidth = plusHeight
//move the initial point of the path
//to the start of the horizontal stroke
plusPath.moveToPoint(CGPoint(x:bounds.width/2 - plusWidth/2 + 0.5, y:bounds.height/2 + 0.5))
//add a point to the path at the end of the stroke
plusPath.addLineToPoint(CGPoint(x:bounds.width/2 + plusWidth/2 + 0.5, y:bounds.height/2 + 0.5))
//Vertical Line
//move to the start of the vertical stroke
plusPath.moveToPoint(CGPoint(x:bounds.width/2 + 0.5, y:bounds.height/2 - plusWidth/2 + 0.5))
//add the end point to the vertical stroke
plusPath.addLineToPoint(CGPoint(x:bounds.width/2 + 0.5, y:bounds.height/2 + plusWidth/2 + 0.5))
//set the stroke color
UIColor.whiteColor().setStroke()
//draw the stroke
plusPath.stroke()
}
}
And your result will be:
You can refer THIS sample project for more Info. And you can modify it as per your need.
Hope It will help you.

Resources