Skip to content

Instantly share code, notes, and snippets.

@qtxie
Forked from debuggerman/AttributedString.m
Created September 1, 2016 07:33
Show Gist options
  • Save qtxie/e48a6e3ee38b5d1edc3cdc205bffbbbd to your computer and use it in GitHub Desktop.
Save qtxie/e48a6e3ee38b5d1edc3cdc205bffbbbd to your computer and use it in GitHub Desktop.
Using attributed string
CFMutableAttributedStringRef attributedString = NULL;
CFRange stringRange = CFRangeMake(0, CFAttributedStringGetLength(attributedString));
//color
CGColorRef stringColor = nil;
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat colorComponents[] = {0.0f, 0.0f, 0.0f, 1.0f};
stringColor = CGColorCreate(rgbColorSpace, colorComponents);
CGColorSpaceRelease(rgbColorSpace);
CFAttributedStringSetAttribute(
attributedString,
stringRange,
kCTForegroundColorAttributeName,
stringColor);
//font
CTFontRef font = nil;
CTFontDescriptorRef mainDescriptor = CTFontDescriptorCreateWithNameAndSize((CFStringRef)@"AGaramondPro-Regular", 0.0);
font = CTFontCreateWithFontDescriptor(mainDescriptor, FONT_SIZE, NULL);
CFAttributedStringSetAttribute(attributedString, stringRange, kCTFontAttributeName, font);
//paragraph
CTTextAlignment alignment = kCTRightTextAlignment;
CGFloat lineSpacing = -30.0f;
CGFloat paragraphSpacing = 10.0f;
CTParagraphStyleSetting _settings[] = {
{kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment},
{kCTParagraphStyleSpecifierMaximumLineSpacing, sizeof(lineSpacing), &lineSpacing},
{kCTParagraphStyleSpecifierParagraphSpacing, sizeof(paragraphSpacing), &paragraphSpacing}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));
// set paragraph style attribute
CFAttributedStringSetAttribute(attributedString, stringRange, kCTParagraphStyleAttributeName, paragraphStyle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment