Canvas в отдельном файле

This commit is contained in:
2025-12-18 22:24:20 +03:00
parent bb825d0225
commit 4f0fb09185
3 changed files with 94 additions and 72 deletions

82
src/Canvas.zig Normal file
View File

@@ -0,0 +1,82 @@
const std = @import("std");
const dvui = @import("dvui");
const Color = dvui.Color;
const Canvas = @This();
allocator: std.mem.Allocator,
texture: ?dvui.Texture = null,
width: u32 = 400,
height: u32 = 300,
pos: dvui.Point = dvui.Point{ .x = 0, .y = 0 },
scroll: dvui.ScrollInfo = .{
.vertical = .given,
.horizontal = .given,
.virtual_size = .{ .w = 2000, .h = 2000 },
},
pub fn init(allocator: std.mem.Allocator) Canvas {
return .{ .allocator = allocator };
}
pub fn deinit(self: *Canvas) void {
if (self.texture) |texture| {
dvui.Texture.destroyLater(texture);
self.texture = null;
}
}
/// Заполнить canvas случайным цветом на CPU
pub fn fillRandomColor(self: *Canvas) !void {
var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));
const random = prng.random();
// Выделить буфер пиксельных данных
const pixels = try self.allocator.alloc(Color.PMA, @as(usize, self.width) * self.height);
defer self.allocator.free(pixels);
// Заполнить случайными цветами
const r = random.int(u8);
const g = random.int(u8);
const b = random.int(u8);
var prev: dvui.Color.PMA = .{ .r = r, .g = g, .b = b, .a = 255 };
for (pixels) |*pixel| {
const r_delta = random.intRangeAtMost(i16, -1, 1);
const g_delta = random.intRangeAtMost(i16, -1, 1);
const b_delta = random.intRangeAtMost(i16, -1, 1);
const r_new: i16 = @as(i16, prev.r) + r_delta;
const g_new: i16 = @as(i16, prev.g) + g_delta;
const b_new: i16 = @as(i16, prev.b) + b_delta;
pixel.* = .{
.r = @intCast(std.math.clamp(r_new, 0, 255)),
.g = @intCast(std.math.clamp(g_new, 0, 255)),
.b = @intCast(std.math.clamp(b_new, 0, 255)),
.a = 255,
};
prev = pixel.*;
}
// Удалить старую текстуру
if (self.texture) |tex| {
dvui.Texture.destroyLater(tex);
}
// Создать новую текстуру из пиксельных данных
self.texture = try dvui.textureCreate(pixels, self.width, self.height, .linear);
// Дать скроллам ощутимый диапазон сразу (минимум 2000x2000)
self.scroll.virtual_size = .{
.w = @max(2000, @as(f32, @floatFromInt(self.width))),
.h = @max(2000, @as(f32, @floatFromInt(self.height))),
};
}
/// Отобразить canvas в UI
pub fn render(self: Canvas, rect: dvui.Rect.Physical) !void {
if (self.texture) |texture| {
try dvui.renderTexture(texture, .{ .r = rect }, .{});
}
}