0

I want use the object - NSTextField to display an image. But the result isn't correct.

the image size is 32x32.

my code like this:

class ViewController: NSViewController {

var text: NSTextField!

override func viewDidLoad() {
    super.viewDidLoad()

    text = NSTextField(frame: NSRect(origin: CGPoint(x: 200, y: 200), size: CGSize(width: 32, height: 32)))
    text.backgroundColor = .clear
    text.isBordered = true
    text.isEditable = false

    let attachment = NSTextAttachment()
    attachment.image = NSImage(named: NSImage.Name(rawValue: "Group_8"))
    attachment.bounds = NSRect(origin: .zero, size: (attachment.image?.size)!)

    let string = NSAttributedString(attachment: attachment)

    text.attributedStringValue = string

    view.addSubview(text)


    // Do any additional setup after loading the view.
}

The final displayed like this:

enter image description here

Why white blank areas appear?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Henry
  • 107
  • 1
  • 3
  • 10
  • It would look weird if the text touches the border. `NSImageView` is more suitable for displaying images. – Willeke Mar 30 '18 at 14:37

2 Answers2

0

While I agree with @Willeke that you should be using an NSImageView, what you're seeing is the NSTextField's "bezel".

You can disable it by adding

text.isBezeled = false

to your code.

Willeke
  • 14,578
  • 4
  • 19
  • 47
smee
  • 231
  • 1
  • 5
  • `NSTextView` or `NSTextField`? Will the border still be visible? – Willeke Apr 01 '18 at 00:48
  • NSTextField: https://developer.apple.com/documentation/appkit/nstextfield/1399435-isbezeled. Yes, the border will still be visible, though it's very close in colour to the background of your image, so it will be hard to see. – smee Apr 01 '18 at 07:57
  • The documentation of `isBezeled` says "if NO, the receiver does not draw a border.". `isBezeled` must be set before `isBordered`. – Willeke Apr 01 '18 at 10:43
  • You're correct. There is no border if the bezel is disabled - an artifact of the image I was using. – smee Apr 01 '18 at 11:03
  • I find the answer at https://stackoverflow.com/a/14038008/1039703, thank you both – Henry Apr 02 '18 at 01:59
0

You can set the property : lineFragmentPadding = 0 . the white padding will disappear.

Beacuse the reason is that :

The padding appears at the beginning and end of the line fragment rectangles. The layout manager uses this value to determine the layout width. The default value of this property is 5.0.

Henry
  • 107
  • 1
  • 3
  • 10