//下面是用coreText 实现
//UILabel中对应的点Pt在UILabel中所有的字体属性
-(NSDictionary*)textAttributesAtPoint:(CGPoint)pt withLabel:(UILabel*)lab
{
// Locate the attributes of the text within the label at the specified point
NSDictionary* dictionary =nil;
// First, create a CoreText framesetter
CTFramesetterRefframesetter =CTFramesetterCreateWithAttributedString((__bridgeCFAttributedStringRef)lab.attributedText);
CGMutablePathRefframePath =CGPathCreateMutable();
CGPathAddRect(framePath,NULL,CGRectMake(0,0, lab.frame.size.width, lab.frame.size.height));
// Get the frame that will do the rendering.
CFRangecurrentRange =CFRangeMake(0,0);
CTFrameRefframeRef =CTFramesetterCreateFrame(framesetter, currentRange, framePath,NULL);
CGPathRelease(framePath);
// Get each of the typeset lines
NSArray*lines = (__bridgeid)CTFrameGetLines(frameRef);
CFIndexlinesCount = [linescount];
CGPoint*lineOrigins = (CGPoint*)malloc(sizeof(CGPoint) * linesCount);
CTFrameGetLineOrigins(frameRef,CFRangeMake(0, linesCount), lineOrigins);
CTLineRefline =NULL;
CGPointlineOrigin =CGPointZero;
// Correct each of the typeset lines (which have origin (0,0)) to the correct orientation (typesetting offsets from the bottom of the frame)
CGFloatbottom = lab.frame.size.height;
for(CFIndexi =0; i < linesCount; ++i) {
lineOrigins[i].y= lab.frame.size.height- lineOrigins[i].y;
bottom = lineOrigins[i].y;
}
// Offset the touch point by the amount of space between the top of the label frame and the text
pt.y-= (lab.frame.size.height- bottom)/2;
// Scan through each line to find the line containing the touch point y position
for(CFIndexi =0; i < linesCount; ++i) {
line = (__bridgeCTLineRef)[linesobjectAtIndex:i];
lineOrigin = lineOrigins[i];
CGFloatdescent, ascent;
CGFloatwidth =CTLineGetTypographicBounds(line, &ascent, &descent,nil);
if(pt.y< (floor(lineOrigin.y) +floor(descent))) {
// Cater for text alignment set in the label itself (not in the attributed string)
if(lab.textAlignment==NSTextAlignmentCenter) {
pt.x-= (lab.frame.size.width- width)/2;
}elseif(lab.textAlignment==NSTextAlignmentRight) {
pt.x-= (lab.frame.size.width- width);
}
// Offset the touch position by the actual typeset line origin. pt is now the correct touch position with the line bounds
pt.x-= lineOrigin.x;
pt.y-= lineOrigin.y;
// Find the text index within this line for the touch position
CFIndexi =CTLineGetStringIndexForPosition(line, pt);
// Iterate through each of the glyph runs to find the run containing the character index
NSArray* glyphRuns = (__bridgeid)CTLineGetGlyphRuns(line);
CFIndexrunCount = [glyphRunscount];
for(CFIndexrun=0; run
CTRunRefglyphRun = (__bridgeCTRunRef)[glyphRunsobjectAtIndex:run];
CFRangerange =CTRunGetStringRange(glyphRun);
if(i >= range.location&& i<= range.location+range.length) {
dictionary = (__bridgeNSDictionary*)CTRunGetAttributes(glyphRun);
break;
}
}
if(dictionary) {
break;
}
}
}
free(lineOrigins);
CFRelease(frameRef);
CFRelease(framesetter);
returndictionary;
}