Home
A few months later, I found much better and easier way, without hacking around.
You need to create gradient filled image file, and let UILabel use it as fill:

UILabel *titleLabel = [[UILabel alloc] init];
  
NSString *path = [[NSBundle mainBundle] pathForResource:@"pattern.black" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
  
titleLabel.textColor = [UIColor colorWithPatternImage:image];
titleLabel.frame = textFrame;
titleLabel.shadowColor = [UIColor whiteColor];
titleLabel.shadowOffset = CGSizeMake(0, -1);
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = UITextAlignmentCenter;
titleLabel.text = "Hello";

Смайлики

  • Nov. 25th, 2008 at 12:05 AM

Сидит Жопс с утра. Делать нех, копипаст влом, но надо что-то намутить дабы повысить продажи. Дай, думает, намучу кавайные няки смайлики, да так, чтобы у всех, кроме абонентов SoftBank JP, они включались через ... 

Posted via LiveJournal.app.

Tags:

Рельсы на отдыхе

  • Aug. 25th, 2008 at 11:30 AM
Забористую траву курили Авторы RESTful Rails.
Read <a href="http://silverity.livejournal.com/27704.html">part II</a> for solution I had found since then.

Long story short, I had to draw some labels filled with gradient (for cuteness reasons), and UILabel class didn’t provide me with easy way. So, after few hours of exploring big brother Mac OS X’s reference documentation the Core had cracked and revealed some Graphics gems, pun intended.
I’m going to create class which inherits from UILabel, so I’ll leave basic stuff out.
All we need is to override drawRect method. Comments in code should be rather explanatory.


// Missing in standard headers.
extern void CGFontGetGlyphsForUnichars(CGFontRef, const UniChar[], const CGGlyph[], size_t);

- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();

// Get drawing font.

CGFontRef font = CGFontCreateWithFontName((CFStringRef)[[self font] fontName]);
CGContextSetFont(ctx, font);
CGContextSetFontSize(ctx, [[self font] pointSize]);

// Transform text characters to unicode glyphs.

NSInteger length = [[self text] length];
unichar chars[length];
CGGlyph glyphs[length];
[[self text] getCharacters:chars range:NSMakeRange(0, length)];
CGFontGetGlyphsForUnichars(font, chars, glyphs, length);

// Measure text dimensions.

CGContextSetTextDrawingMode(ctx, kCGTextInvisible);
CGContextSetTextPosition(ctx, 0, 0);
CGContextShowGlyphs(ctx, glyphs, length);
CGPoint textEnd = CGContextGetTextPosition(ctx);

// Calculate text drawing point.

CGPoint alignment = CGPointMake(0, 0);
CGPoint anchor = CGPointMake(textEnd.x * (-0.5), [[self font] pointSize] * (-0.25));
CGPoint p = CGPointApplyAffineTransform(anchor, CGAffineTransformMake(1, 0, 0, -1, 0, 1));

if ([self textAlignment] == UITextAlignmentCenter) {
alignment.x = [self bounds].size.width * 0.5 + p.x;
}
else if ([self textAlignment] == UITextAlignmentLeft) {
alignment.x = 0;
}
else {
alignment.x = [self bounds].size.width - textEnd.x;
}

alignment.y = [self bounds].size.height * 0.5 + p.y;

// Flip back mirrored text.

CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));

// Draw shadow.

CGContextSaveGState(ctx);
CGContextSetTextDrawingMode(ctx, kCGTextFill);
CGContextSetFillColorWithColor(ctx, [[self shadowColor] CGColor]);
CGContextSetShadowWithColor(ctx, [self shadowOffset], 0, [[self shadowColor] CGColor]);
CGContextShowGlyphsAtPoint(ctx, alignment.x, alignment.y, glyphs, length);
CGContextRestoreGState(ctx);

// Draw text clipping path.

CGContextSetTextDrawingMode(ctx, kCGTextClip);
CGContextShowGlyphsAtPoint(ctx, alignment.x, alignment.y, glyphs, length);

// Restore text mirroring.

CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);

// Fill text clipping path with gradient.

CGPoint start = CGPointMake(rect.origin.x, rect.origin.y);
CGPoint end = CGPointMake(rect.origin.x, rect.size.height);
CGContextDrawLinearGradient(ctx, self.gradient, start, end, 0);

// Cut outside clipping path.

CGContextClip(ctx);
}

And here’s the result of all this:
iPhone Simulator

Улыбнись, мир!

  • Jul. 31st, 2008 at 12:38 AM
Softbank JP отжигает:

carrier.plist

У кого же APN «hello.world»? ;)

UPD: Чёрт, они знали, да.

Tags:

eyetv 3 умеет показывать m2ts H.264 поток в 12 Mbps (Full HD) и даже не тормозить, если включить cpu intensive progressive scan. С обычным deinterlace и motion-adaptive малость подлагивает.

О параде в HDV

  • May. 10th, 2008 at 5:07 PM
Как выяснилось, смотреть Blu-Ray без геморроя можно только на PS3, надо брать.
А парад хорош, да, я аж прослезился.

Об играх и оптимизации

  • May. 5th, 2008 at 12:28 AM
Intel Core 2 Duo 2.4 GHz, GeForce 8600M GT 256 Mb, 4 GB RAM.

Neverwinter Nights 2 OS X version:

  • 1920x1200, почти все настройки по максимуму – 11 FPS,

  • 800x600, почти все настройки по максимуму – 11 FPS;

  • 1920x1200, все настройки по минимуму – 12 FPS,

  • 800x600, все настройки по минимуму – 12 FPS.


Убить всех людей.

iphone and apt

  • Apr. 23rd, 2008 at 6:10 AM
Если мы все хотим выглядеть одинаково, то каждый должен создать свой собственный репозитарий: http://iphone.piu.fm.
Have fun.

Tags:

memcpy vs assignment

  • Jan. 31st, 2008 at 8:43 PM

class uint128 {
public:
  uint64 high;
  uint64 low;

  inline void operator = (const uint128& a) {
    ::memcpy(this, &a, sizeof(uint128));
  }
};


class uint128 {
public:
  uint64 high;
  uint64 low;

  inline void operator = (const uint128& a) {
    high = a.high;
    low = a.low;
  }
};


movq	0xf8(%rbp),%rcx
movq	0xf0(%rbp),%rdx
movq	(%rdx),%rax
movq	%rax,(%rcx)
movq	0x08(%rdx),%rax
movq	%rax,0x08(%rcx)


movq	0xf0(%rbp),%rax
movq	(%rax),%rdx
movq	0xf8(%rbp),%rax
movq	%rdx,(%rax)
movq	0xf0(%rbp),%rax
movq	0x08(%rax),%rdx



2nd is faster.

Tags:

My favorite iPhone apps

  • Jan. 28th, 2008 at 2:00 AM
Небольшой список, дабы не забыть:

  • MobileScrobbler — клиент для Last.fm.

  • MobileChat — IM-клиент.

  • Sketches — рисовалка.

  • Русский Проект — русификация.

  • Caterpillar — разные улучшалки.

  • BSD Subsystem — аха.

  • OpenSSH — тоже аха.

  • Term-vt100 — терминал.

  • Customize — кастомайзер тем.

  • Screenshot — название говорит само за себя.

  • Colloquy — IRC-клиент.

  • psx4iphone — эмулятор PS.

  • Books — eBook reader.

  • PDFViewer — PDF reader.

  • Converter — units converter.

  • BossPrefs — выключатель sshd, EDGE, WiFi.

  • iLM — Локальные гуглокарты.


Repositories:

Updated 1/3/2008.

Tags:

iPhone tips&tricks

  • Jan. 25th, 2008 at 9:14 PM

  • Frequent "Call failed" messages: Settings > Phone > Enable "Show my caller id".

  • Boot iPhone or iPod Touch in verbose mode: nvram boot-args="-v", back to normal: nvram boot-args="".

  • SMS delivery reports: "!" before message (works on Beeline).

  • SpringBoard crashes (Apple logo on start): Turn off auto-brightness and auto-lock.

  • Show phone number in iTunes:

    1. SSH to your phone. Do not forget to turn auto-lock off.

    2. Stop the CommCenter: launchctl -w unload /System/Library/LaunchDaemons/com.apple.CommCenter.plist

    3. Start minicom: minicom -s

    4. Then proceed to change the Serial Port device name to /dev/tty.baseband

      • Scroll down to "Serial Port".

      • Press "A" and retype over the serial port device name.

      • Press "ENTER" twice.

      • Scroll down to EXIT and press ENTER.

      • Type "AT" and press ENTER. You should get an "OK" back.


    5. Enter the following commands:

      • AT+CPBS="ON" // This command will set the Address Book storage to "Own Number".

      • AT+CPBW=1,"XXXXXXXXXXXX",,"TTTTT" // This command will write the number (XXXXXXXXXX) with an optional text "TTTT".

      • AT+CPBR=1 // This command will display back whatever you have entered, plus the type, either "129" or "145". It will be "129" if the number fits a "national" pattern and "145" if it's international.

      • AT+CNUM // The fourth command will display the "Own Number". This is the way it's queried, so we try to see the result.



    6. Press "Ctrl-A", "Q" and "ENTER" to exit minicom.

    7. Reload CommCenter: launchctl -w load /System/Library/LaunchDaemons/com.apple.CommCenter.plist

    8. Reboot your iPhone.



Tags:

Сколько стоит воздух?

  • Jan. 23rd, 2008 at 10:02 PM
Маркетологи Apple сообщили журналистам, что представленный недавно ультратонкий MacBook Air в России будет стоить $2800, что на $1000 дороже, чем в США. Устройство может появиться в продаже уже в феврале 2008 г.
CNews


Идем на BHPhotoVideo и видим, что они продают за $1,798.95. Идем дальше, доставка в Россию: UPS Worldwide Saver (3-5 business days delivery) — $149.90, FedEx Priority (3-5 business days delivery) — $244.00. Итого: $1,948.85 или $2,042.95, в зависимости от службы доставки. И в любом случае, ниже чем у Бутмана. Это, извините за мой французский, пиздец, господа.

Tags:

iPhone

  • Dec. 22nd, 2007 at 11:36 PM
Импульсивно пошел и купил. :)

Tags:

На правах

  • Dec. 9th, 2007 at 6:07 AM
А я вот поддамся общей тенденции, хоть меня тысячи и не читают.

Утконос – сколько его ни знаю, опаздывает с доставкой стабильно на 2-3 часа (максимум был на 7), и там отвратительно обрабатываются отсутствующие позиции (особенно в той части, когда их просто тихо не привозят). Может, я что-то неправильно делаю, ибо некоторая часть выбранного мною всегда отсутствует (эта часть, растет ближе к weekend-у, и достигает отметки в 90%).

Седьмой континент – отличается большей пунктуальностью, дельта времени доставки варьируется в пределах <2 часов. По поводу отсутсвующих позиций (которых меньше, чем в удконозе) перезванивают сами и предлагают чего-нибудь на замену (хотя не сразу сообразишь, какие из 5 видов огурцов нужно выбрать). Но, извините меня, цены процентов на 20 выше.

Ашан – лошан, ибо далеко. А ездить ногами мне лень, мышью куда удобнее.

Вот и где теперь искать счастья™?

P.S. Пост не был спонсирован Google Inc., к моему сожалению.

Look-behind

  • Dec. 9th, 2007 at 5:48 AM
О некоторых — я действительно могу...

Tags:

using terms from application "Mail"
	on perform mail action with messages theMessages for rule theRule
		repeat with eachMessage in theMessages
			if eachMessage's mailbox's name is "All Mail" then
				set read status of eachMessage to true
			end if
		end repeat
	end perform mail action with messages
end using terms from

Scientology

  • Dec. 1st, 2007 at 9:11 AM
Как же изощрённо и в то же время просто можно зомбировать людей.

Tags:

Latest Month

February 2009
S M T W T F S
1234567
891011121314
15161718192021
22232425262728

Advertisement

Stuff

My Wishlist

Syndicate

RSS Atom
Powered by LiveJournal.com