void renderTextToTexture(GLuint textureId, int width, int height) {
if (!grContext) {
LOGE("GrContext not initialized.");
return;
}
// 1. Gắn textureId vào FBO
GLuint fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("Framebuffer is not complete: 0x%x", status);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
return;
}
// 2. Wrap textureId thành GrBackendTexture
GrGLTextureInfo texInfo;
texInfo.fID = textureId;
texInfo.fTarget = GL_TEXTURE_2D;
texInfo.fFormat = GL_RGBA8;
GrBackendTexture backendTexture(width, height, GrMipmapped::kNo, texInfo);
SkColorType colorType = kRGBA_8888_SkColorType;
auto surface = SkSurfaces::WrapBackendTexture(
grContext.get(),
backendTexture,
kBottomLeft_GrSurfaceOrigin,
colorType,
SkColorSpace::MakeSRGB(),
nullptr
);
if (!surface) {
LOGE("Failed to create surface from textureId.");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
return;
}
// 3. Vẽ chữ vào surface này
SkCanvas* canvas = surface->getCanvas();
canvas->clear(SK_ColorTRANSPARENT);
SkPaint paint;
paint.setColor(SK_ColorBLACK);
paint.setAntiAlias(true);
sk_sp<SkFontMgr> fontMgr = SkFontMgr_New_Custom_Directory("/system/fonts");
sk_sp<SkTypeface> typeface = fontMgr->matchFamilyStyle("Roboto", SkFontStyle());
SkFont font(typeface, 48);
canvas->drawString("Hello from Skia to Texture", 50, 100, font, paint);
grContext->flushAndSubmit();
// 4. Dọn FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
LOGI("Successfully rendered text to textureId: %u", textureId);
}