简体   繁体   English

NSTextView中的圆角和渐变

[英]Rounded corners and gradients in NSTextView

I'm using NSAttributedString inside a NSTextView to highlight certain areas within the text. 我在NSTextView中使用NSAttributedString来突出显示文本中的某些区域。 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 : 我已经创建了一个NSTextView实现,它实现了与你想要创建的非常相似的外观(只缺少渐变),实现可以在这里找到: 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 这里有一篇博客文章解释了我的方法: http//aimannajjar.com/blog/1-How-to-Create-NSTextView-with-Facebook-like-Tags-Mentions.html#post

You can do rounded corner with Quartz lib : 你可以用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. 您可以尝试使用NSTextAttachmentCell,以便自定义渲染角点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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