简体   繁体   中英

Rounded corners and gradients in NSTextView

I'm using NSAttributedString inside a NSTextView to highlight certain areas within the text. I found it easy to change the background color and the text color, but I don't even know where to start on drawing more sophisticated things like rounded corners or background gradients, or borders.

Here's a picture of what I'm trying to achieve:

突出显示的文本样机

This is totally doable in a web view, but that seems like overkill for just a few extra graphic flourishes.

I've created an NSTextView implementation that achieves very similar look to the one you're looking to create (only the gradient is missing), the implementation is available here: http://github.com/aiman86/ANTaggedTextView : 在此输入图像描述

And here's a blog post explaining my approach: http://aimannajjar.com/blog/1-How-to-Create-NSTextView-with-Facebook-like-Tags-Mentions.html#post

You can do rounded corner with Quartz lib :

[view.layer setCornerRadius:7.0];

Everyting is possible but not as easy as a stylesheet !

You can set attributes on the range of text you want to highlight in one of two ways:

NSTextView *textView = ...;
NSRange rangeToHighlight = ...; // Range of characters in textView's textStorage
NSColor *highlightColor = ...;

// Method 1: less efficient
[textView.textStorage setAttributes:@{ NSForegroundColorAttributeName : highlightColor } range:rangeToHighlight];

// Method 2: more efficient but only works for attributes that don't affect layout, e.g. color, underline etc.
[textView.layoutManager addTemporaryAttribute:NSForegroundColorAttributeName value:highlightColor forCharacterRange:rangeToHighlight];

I'm not sure if you can use a gradient color, but solid colors certainly work.

This won't get you the rounded corners though.

You might try an NSTextAttachmentCell so you can custom render the corners.

有一些解决这个问题的方法可能对你有所帮助,创建一个带圆角的UIView,然后尝试在其中绘制NSTextView,它应该可以工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM