I am trying to build a custom MKOverlayRenderer subclass which will display an image and text presented on top of some type of subview based on this answer. At my current stage of implementing this I have gotten the image to appear on the map but now I am trying to add text over the image.
The text is appearing upside down and flipped on top of the image. The image appears to be oriented correctly using the same rectangle and same context. What am I doing wrong how do I go about implementing this?
This is the code pertaining to drawing the text:
UIGraphicsPushContext(context);
// ...
UIGraphicsPushContext(context);
UIColor.black.setStroke()
context.setLineWidth(1)
context.stroke(rect.insetBy(dx: 0.5, dy: 0.5))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [NSAttributedString.Key.paragraphStyle : paragraphStyle,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 100.0),
NSAttributedString.Key.foregroundColor : UIColor.black]
"\(rect.size)".draw(in: rect, withAttributes: attributes)
UIGraphicsPopContext();
Class in its Entirety
class CustomOverlayView:MKOverlayRenderer{
var overlayImage:UIImage
init(overlay:MKOverlay,image:UIImage){
self.overlayImage = #imageLiteral(resourceName: "DSC00042")
super.init(overlay: overlay)
}
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
super.draw(mapRect, zoomScale: zoomScale, in: context)
guard let imageReference = overlayImage.cgImage else { return }
var rect = self.rect(for: overlay.boundingMapRect)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -rect.size.height)
context.draw(imageReference, in: rect)
UIGraphicsPushContext(context);
// ...
UIGraphicsPushContext(context);
UIColor.black.setStroke()
context.setLineWidth(1)
context.stroke(rect.insetBy(dx: 0.5, dy: 0.5))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [NSAttributedString.Key.paragraphStyle : paragraphStyle,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 100.0),
NSAttributedString.Key.foregroundColor : UIColor.black]
"\(rect.size)".draw(in: rect, withAttributes: attributes)
UIGraphicsPopContext();
}
}
Related
I have a camera which provides me UIImage with resolution of 1920x1080, I have implemented a system where I can add UITextViews as subviews and my goal is to add them to the original UIImage and export a final Image of the resolution of 1920x1080.
So the procedure I have been thinking about is this:
I add upperView over view.frame which is responsible of drawing all the textViews present on screen.
Then I want to add this view over the original UIImage scaling it proportionally
This is the code I implemented in order to do it:
func passingAndDrawingTextViews(textViews : [UITextView], viewPassed : UIView, inImage : UIImage) -> UIImage{
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(viewPassed.frame.size, false, scale)
viewPassed.draw(CGRect(x: 0, y: 0, width: viewPassed.frame.width, height: viewPassed.frame.height))
//adding each textView
textViews.forEach { (textView) in
let textColor = textView.textColor
let textFont = UIFont(name: textView.font!.fontName, size: textView.font!.pointSize)
let textAlignment = textView.textAlignment
//alignment of the text
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle : paragraphStyle,
]
let rect = CGRect(x: textView.frame.minX + textView.textContainer.lineFragmentPadding, y: textView.frame.minY + textView.textContainerInset.top, width: textView.frame.width, height: textView.frame.height)
textView.text.draw(in: rect, withAttributes: textFontAttributes as [NSAttributedString.Key : Any])
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(inImage.size)
let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height)
inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
newImage!.draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
In the function I respectively pass the list of textViews, the upperView, and the originalImage.
But the problem is that the textView I get are stretched on the x axis. I don't know why this happens.
What I get:
What I want
the rect you are passing in this line :
newImage!.draw(in: rect)
is actually the size of screen it self so the image will strech to fill this rect.
so make this :
let rect = CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height)
the size of the image you are passing in.
i have a function which draw text on image but issue is when i call this function it gives a error "Argument labels '(_:, _:)' do not match any available overloads"
i am new to swift and dont know how to fix
func write_text_on_image(drawtext text:NSString , inimage img : UIImage , atpoint point : CGPoint) -> UIImage {
let textcolor = UIColor.white
let font = UIFont(name: "Helvetica", size: 16)
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(img.size, false, scale)
let font_attributes = [
kCTFontAttributeName : font,
kCTForegroundColorAttributeName : textcolor
]
img.draw(in: CGRect(origin: CGPoint.zero, size: img.size))
let rect = CGRect(origin: point, size: img.size)
text.draw(in: rect, withAttributes: font_attributes as [NSAttributedString.Key : Any])
let newimg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndPDFContext()
return newimg!
}
i am calling this func as
write_text_on_image(drawtext: "THis is some text", inimage: UIImage(named: "test.png")!, atpoint: CGPoint(20,20))[!
check out screen of function []1
As #vadian said, code completion would help you. This is what I got from duplicating a fragment in Playground:
func write_text_on_image(drawtext text:NSString , inimage img : UIImage , atpoint point : CGPoint) -> UIImage { return UIImage() }
write_text_on_image(drawtext: "NSString", inimage: UIImage(), atpoint: CGPoint(x: 0, y: 0))
Doesn't do anything, but compiles.
CGPoint(x,y) pass perameter as CGPoint(x : value,y ; value)
I have the following code to draw a text over an NSImage.
But the resulting image is getting resized to smaller one when I save it to disk.
What i'm i doing wrong? Please advice
func drawText(image :NSImage) ->NSImage
{
let text = "Sample Text"
let font = NSFont.boldSystemFont(ofSize: 18)
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5)
let textStyle = NSMutableParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: NSColor.white,
NSParagraphStyleAttributeName: textStyle
]
let im:NSImage = NSImage(size: image.size)
let rep:NSBitmapImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(image.size.width), pixelsHigh: Int(image.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
im.addRepresentation(rep)
im.lockFocus()
image.draw(in: imageRect)
text.draw(in: textRect, withAttributes: textFontAttributes)
im.unlockFocus()
return im
}
This is a different approach using a temporary NSView to draw the image and the text and cache the result in a new image (code is Swift 4). The benefit it you don't need to deal with pixels
class ImageView : NSView {
var image : NSImage
var text : String
init(image: NSImage, text: String)
{
self.image = image
self.text = text
super.init(frame: NSRect(origin: NSZeroPoint, size: image.size))
}
required init?(coder decoder: NSCoder) { fatalError() }
override func draw(_ dirtyRect: NSRect) {
let font = NSFont.boldSystemFont(ofSize: 18)
let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5)
image.draw(in: dirtyRect)
text.draw(in: textRect, withAttributes: [.font: font, .foregroundColor: NSColor.white])
}
var outputImage : NSImage {
let imageRep = bitmapImageRepForCachingDisplay(in: frame)!
cacheDisplay(in: frame, to:imageRep)
let tiffData = imageRep.tiffRepresentation!
return NSImage(data : tiffData)!
}
}
To use it, initialize a view
let image = ... // get some image
let view = ImageView(image: image, text: "Sample Text")
and get the new image
let imageWithText = view.outputImage
Note:
The paragraph style is not used at all, but if you want to create a mutable paragraph style just write
let textStyle = NSMutableParagraphStyle()
Mixed pixel vs point?
Depending on your screen 2x or 3x image is smaller 2 times or 3 times?
Here is more detailed info (scroll down to "Converting between pixels and points")
http://blog.fluidui.com/designing-for-mobile-101-pixels-points-and-resolutions/
But keep in mind that:
NSImage is resolution aware and uses a HiDPI graphics context when you lockFocus on a system with retina screen.
The image dimensions you pass to your NSBitmapImageRep initializer are in points (not pixels). An 150.0 point-wide image therefore uses 300 horizontal pixels in a #2x context.
Source:
How to save PNG file from NSImage (retina issues)
Following simple app works for me. Enjoy ;)
import Cocoa
class ViewController: NSViewController {
func save(image:NSImage, imageURL:String, format:String) -> Bool
{
let bMImg = NSBitmapImageRep(data: (image.tiffRepresentation)!)
switch format {
case ".png":
let filepath = URL(fileURLWithPath: imageURL+".png")
let dataToSave = bMImg?.representation(using: NSBitmapImageRep.FileType.png, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 1])
do
{
try dataToSave?.write(to: filepath)
return true
} catch {
return false
}
default:
return false
}
}
func draw(text:String, image:NSImage) -> NSImage
{
let font = NSFont.boldSystemFont(ofSize: 18)
let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedStringKey.font: font,
NSAttributedStringKey.foregroundColor: NSColor.white,
NSAttributedStringKey.paragraphStyle: textStyle
]
let im:NSImage = NSImage(size: image.size)
let rep:NSBitmapImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(image.size.width), pixelsHigh: Int(image.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0)!
im.addRepresentation(rep)
im.lockFocus()
image.draw(in: imageRect)
text.draw(in: textRect, withAttributes: textFontAttributes)
im.unlockFocus()
return im
}
#IBAction func action(_ sender: NSButton) {
let dialog = NSOpenPanel();
dialog.title = "Choose a image...";
dialog.showsResizeIndicator = true;
dialog.showsHiddenFiles = false;
dialog.canChooseDirectories = true;
dialog.canCreateDirectories = true;
dialog.allowsMultipleSelection = false;
dialog.allowedFileTypes = ["png", "jpg"];
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
guard let url = dialog.url,
let imageCIImage = CIImage(contentsOf: url) else {
return
}
let rep: NSCIImageRep = NSCIImageRep(ciImage: imageCIImage)
let nsImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
let imageWithText = draw(text:"ABC", image: nsImage)
if (save(image: imageWithText, imageURL: "imageWithText", format: ".png")) {
print("Success")
} else {
print("ERROR:Failed to save image")
}
} else {
// User clicked on "Cancel"
return
}
}
}
I am changing the color of a UISlider by calling .thumbTintColor
#IBAction func slider1Master(sender: AnyObject) {
slider1.thumbTintColor = UIColor.orangeColor()}
It works, but I want the color to change back to it's original state when the touch ends (user lifts finger).
Does anyone have any suggestions? Thank you.
You can use "setThumbImage" instead.
Then you have the option of setting an image for a specific state of action.
For the image, just create a rounder image with the color you desire.
//Creating an Image with rounded corners:
extension UIImage {
class func createThumbImage(size: CGFloat, color: UIColor) -> UIImage {
let layerFrame = CGRectMake(0, 0, size, size)
let shapeLayer = CAShapeLayer()
shapeLayer.path = CGPathCreateWithEllipseInRect(layerFrame.insetBy(dx: 1, dy: 1), nil)
shapeLayer.fillColor = color.CGColor
shapeLayer.strokeColor = color.colorWithAlphaComponent(0.65).CGColor
let layer = CALayer.init()
layer.frame = layerFrame
layer.addSublayer(shapeLayer)
return self.imageFromLayer(layer)
}
class func imageFromLayer(layer: CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, UIScreen.mainScreen().scale)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
//Setting the image for a selected state of UISlider:
func setupSlider() {
let size:CGFloat = 12
let highlightedStateOrangeColorImage = UIImage.createThumbImage(size, color: UIColor.orangeColor())
let defaultStateBlueColorImage = UIImage.createThumbImage(size, color: UIColor.blueColor())
self.slider.setThumbImage(highlightedStateOrangeColorImage, forState: UIControlState.Highlighted)
self.slider.setThumbImage(defaultStateBlueColorImage, forState: UIControlState.Normal)
}
You can safely accept McMatan’s solution as your answer. It is good for several reasons.
the colour changes back to its original state when the user lifts a finger, as you requested
using the extension to create a shape does away with image assets for the UISlider
it could also be used to draw images for circular UIButtons and circular UIViews.
it can also create a shape with colours matching other UISlider design elements (if so desired).
The code below does just that. I used McMatan’s UIImage extension with no changes other than translation to Swift 3. But I have split his function setUpSlider() into two, one for drawing the circular image in its default state, the other for drawing it in its highlighted state.
By accepting McMatan’s solution, you will encourage those who contribute their experience and free time to continue making this forum worthwhile for the rest of us. So please do.
class ViewController: UIViewController {
var slider: UISlider!
let defaultColour = UIColor.blue
let highlightedColour = UIColor.orange
let thumbSize = 20
override func viewDidLoad() {
super.viewDidLoad()
slider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 23))
slider.minimumValue = 0
slider.minimumTrackTintColor = defaultColour
slider.maximumValue = 100
slider.maximumTrackTintColor = highlightedColour
slider.center = view.center
slider.value = slider.maximumValue / 2.0
let highlightedImage = makeHighlightedImage()
let defaultImage = makeDefaultImage()
slider.setThumbImage(highlightedImage, for: UIControlState.highlighted)
slider.setThumbImage(defaultImage, for: UIControlState.normal)
slider.isContinuous = false
view.addSubview(slider)
slider.addTarget(self, action: #selector(sliderValueChanged), for: UIControlEvents.valueChanged)
}
func sliderValueChanged(sender: UISlider){
print(sender.value)
}
func makeHighlightedImage() -> (UIImage) {
let size = CGFloat(thumbSize)
let highlightedStateImage = UIImage.createThumbImage(size: size, color: highlightedColour)
return (highlightedStateImage)
}
func makeDefaultImage() -> (UIImage) {
let size = CGFloat(thumbSize)
let defaultStateImage = UIImage.createThumbImage(size: size, color: defaultColour)
return (defaultStateImage)
}
}
Extension translated to Swift 3
import UIKit
extension UIImage {
class func createThumbImage(size: CGFloat, color: UIColor) -> UIImage {
let layerFrame = CGRect(x: 0, y: 0, width: size, height: size)
let shapeLayer = CAShapeLayer()
shapeLayer.path = CGPath(ellipseIn: layerFrame.insetBy(dx: 1, dy: 1), transform: nil)
shapeLayer.fillColor = color.cgColor
shapeLayer.strokeColor = color.withAlphaComponent(0.65).cgColor
let layer = CALayer.init()
layer.frame = layerFrame
layer.addSublayer(shapeLayer)
return self.imageFromLayer(layer: layer)
}
class func imageFromLayer(layer: CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, UIScreen.main.scale)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage!
}
}
I came up with an answer similar to MCMatan's but without the need for a UIImage extension:
func setThumbnailImage(for slider: UISlider, thumbnailHeight: CGFloat, thumbnailColor: UIColor) {
let cornerRadius: CGFloat = 25
let rect = CGRect(x: 0, y: 0, width: thumbnailHeight, height: thumbnailHeight)
let size = CGSize(width: thumbnailHeight, height: thumbnailHeight)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
// this is what makes it round
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
thumbnailColor.setFill()
UIRectFill(rect)
if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
slider.setThumbImage(nil, for: .normal)
slider.setThumbImage(newImage, for: .normal)
}
UIGraphicsEndImageContext()
}
To use:
override func viewDidLoad() {
super.viewDidLoad()
setThumbnailImage(for: yourSlider, thumbnailHeight: 20.0, thumbnailColor: UIColor.red)
}
or
func someActionJustFinishedNowUpdateThumbnail() {
setThumbnailImage(for: yourSlider, thumbnailHeight: 40.0, thumbnailColor: UIColor.blue)
}
or
func setThumbnailToSliderHeight() {
let sliderHeight = yourSlider.frame.size.height
setThumbnailImage(for: yourSlider, thumbnailHeight: sliderHeight, thumbnailColor: UIColor.purple)
}
Ok I'm at my wits end. I'm new to MapKit and writing a health stats app that plots data on a MKMapView relative to where patients live. I can drop annotations, and draw polygons of postcode areas with no problem.
However I'd like to write text on the map polygon (and not an annotation).
Here's my code, I've subclassed MKPolygonRender to access drawRect.
Polygons are perfect but no text. I've tried write to the first point in the polygon (I will find centre eventually)
Been stuck for several nights so really grateful.
class PolygonRender: MKPolygonRenderer {
var point:CGPoint!
override init(overlay: MKOverlay) {
super.init(overlay: overlay)
}
override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) {
super.drawMapRect(mapRect, zoomScale: zoomScale, inContext: context)
let mapRect:MKMapRect = self.overlay.boundingMapRect
let rect:CGRect = self.rectForMapRect(mapRect)
UIGraphicsPushContext(context)
var bPath = UIBezierPath()
//let polygon:MKPolygon = self.polygon
super.fillColor = UIColor.yellowColor()
let points = self.polygon.points()
let pointCount = self.polygon.pointCount
var point:CGPoint = self.pointForMapPoint(points[0])
bPath.moveToPoint(point)
for var i = 1; i < pointCount; i++ {
point = self.pointForMapPoint(points[i])
bPath.addLineToPoint(point)
}
bPath.closePath()
bPath.addClip()
let roadWidth:CGFloat = MKRoadWidthAtZoomScale(zoomScale)
let attributes: [String: AnyObject] = [
NSForegroundColorAttributeName : UIColor.blackColor(),
NSFontAttributeName : UIFont.systemFontOfSize(5 * roadWidth)]
let centerPoint = pointForMapPoint(points[0])
print(centerPoint)
let string:NSString = "Hello world"
string.drawAtPoint(centerPoint, withAttributes: attributes)
UIGraphicsPopContext()
}
Generally you do it right but I think the font size is too small to see the text.
Try to set font size to value like 100 or bigger to find out the text is there, but you will need to zoom in.
Example:
public override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let rect:CGRect = self.rect(for: mapRect)
UIGraphicsPushContext(context);
// ...
UIGraphicsPushContext(context);
UIColor.black.setStroke()
context.setLineWidth(1)
context.stroke(rect.insetBy(dx: 0.5, dy: 0.5))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [NSAttributedStringKey.paragraphStyle : paragraphStyle,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 100.0),
NSAttributedStringKey.foregroundColor : UIColor.black]
"\(rect.size)".draw(in: rect, withAttributes: attributes)
UIGraphicsPopContext();
}
Image below shows how on the map is displayed text with font size 100 when the rect size is 1024x1024